locked
When not to use auto-implemented properties. RRS feed

  • Question

  • Hi, 

    Both the classes & their properties do pretty much the same thing and give the same result. 

    Question is, why would I ever use the Car2 style of class/properties?

    void Main()
    {
    	Car1 c1 = new Car1();
    	c1.Type = "BMW";
    
    	Car2 c2 = new Car2();
    	c2.Type = "Audi";
    
    	Console.WriteLine (c1.Type);
    	Console.WriteLine (c2.Type);	
    }
    
    
    public class Car1
    {
    	public String Type { get; set;}
    }
    
    public class Car2
    {
    	private String type;
    	public String Type 
    	{ 
    		get {return type;}
    		set {type=value;}
    	}
    }

    Thursday, December 13, 2012 2:58 PM

Answers

  • HI,

    Properties are similar to methods , but here you have more control .They have dual behaviour .For user code properties behave like field , but where it is implemented it is like a method (through set and get blocks).

    But sometimes you do not need any logic over data, then you can use autoimplemented properties .

    But when you need to perform some logic while setting or getting the data , you will use Car2 type of implementation because in get and set sections of property you can implement some logic .

     public class Student
        {
            private string _Name = "";
    
            public string Name
            {
                get { return _Name; }
                set { _Name = value.Trim().ToUpper(); }
            }
        }

    As you can see in the above code , Name property will always return Trimmed and Uppercase Name , despite what was assigned to it .

    But if you don't need such extra logic you can use autoimplemented property .

    Hope this helps .


    One good question is equivalent to ten best answers.


    Thursday, December 13, 2012 3:44 PM
  • If you're only setting the backing variable in the setter, only returning the backing variable in the getter, and never need to access the underlying field outside of the property, then you can use an auto implemented property.  Any time any of those aren't true, you can't use an auto-implemented property

    Common examples are returning derived data, i.e. there is no backing field, performing validation of data in setters, firing property changed events in setters, having a property that doesn't store it's data in a private field (i.e. getting/setting a "Session" value).

    Thursday, December 13, 2012 3:31 PM

All replies

  • When you need to perform additional validation in the setter, then you have to manually manage the backing store.

    "Premature optimization is the root of all evil." - Knuth

    If I provoked thought, please click the green arrow

    If I provoked Aha! please click Propose as Answer

    We are here to learn, to share knowledge, and to earn points; all in about equal measure.


    Thursday, December 13, 2012 3:01 PM
  • If you're only setting the backing variable in the setter, only returning the backing variable in the getter, and never need to access the underlying field outside of the property, then you can use an auto implemented property.  Any time any of those aren't true, you can't use an auto-implemented property

    Common examples are returning derived data, i.e. there is no backing field, performing validation of data in setters, firing property changed events in setters, having a property that doesn't store it's data in a private field (i.e. getting/setting a "Session" value).

    Thursday, December 13, 2012 3:31 PM
  • HI,

    Properties are similar to methods , but here you have more control .They have dual behaviour .For user code properties behave like field , but where it is implemented it is like a method (through set and get blocks).

    But sometimes you do not need any logic over data, then you can use autoimplemented properties .

    But when you need to perform some logic while setting or getting the data , you will use Car2 type of implementation because in get and set sections of property you can implement some logic .

     public class Student
        {
            private string _Name = "";
    
            public string Name
            {
                get { return _Name; }
                set { _Name = value.Trim().ToUpper(); }
            }
        }

    As you can see in the above code , Name property will always return Trimmed and Uppercase Name , despite what was assigned to it .

    But if you don't need such extra logic you can use autoimplemented property .

    Hope this helps .


    One good question is equivalent to ten best answers.


    Thursday, December 13, 2012 3:44 PM

  • 3. AIPs put additional overhead on CLR for creating private variables dynamically and maintaining these variables.

    That's interesting.  I kind of though they did exactly the same thing but you are saying it's less efficient to 

    let the CLR create the private variables instead of defining them in the code.  

    Thursday, December 13, 2012 4:25 PM
  • They are no different than exposing the members directly.

    Wrong. A property is still a property, even if auto-implemented. If you ever change a field to a property, you need to recompile every assembly referencing that one. If you add implementation to an auto-implemented property, you don't need to recompile them.

    You can't have any implemention inside getter or setters.

    That's the purpose of auto-implemented properties. If you need additional implementation, change the auto-implemented property to an explicitly implemented property.

    If the AIP type is string, then the default value will be null instead of string.Empty. So, you got to explicitly initialize the AIP.

    The null value is a sensible default value for a string.

    AIPs put additional overhead on CLR for creating private variables dynamically and maintaining these variables.

    Wrong. The backing field is generated at compile-time.

    I believe, AIPs were originated for the reason of Anonymous Types. I mean, when you create an anonymous type as below, the properties should be auto implemented.
    var anonType = new { FirstName = "Adavesh", LastName = "Mangaon" };
    In this case CLR automatically implements the properties FirstName and LastName. So, only in such cases AIPs are useful. Otherwise, I find them unnecessary.

    Wrong. You don't need to have auto-implemented properties in the language to have auto-generated types.

    Thursday, December 13, 2012 4:39 PM
  • Nice Thanks.

    • Edited by Adavesh Thursday, December 13, 2012 5:10 PM
    Thursday, December 13, 2012 5:09 PM
  • Yeah.. Except the third point, Adavesh's explanation is very good. Actually I think properties themselves are not good, especially when you are using using them in remoting. Anyways, things are there, whether you use or not use.
    Thursday, December 13, 2012 5:50 PM
  •  Actually I think properties themselves are not good, especially when you are using using them in remoting. Anyways, things are there, whether you use or not use.

    Look , OOP construct goes very parallel with real life objects , and Property is no exception. Almost every concept in oops can be visualized from real life point of view .

    If you think Property is not good , have some justification over that ! Then what is right ? Have some suggestions !

    Are you happy with no hair color, no skin color, no testy foods (which are in-fact Properties of objects ).


    One good question is equivalent to ten best answers.

    Thursday, December 13, 2012 6:01 PM
  • Yeah.. Except the third point, Adavesh's explanation is very good. Actually I think properties themselves are not good, especially when you are using using them in remoting. Anyways, things are there, whether you use or not use.

    Really, because I see no value in any of his points.

    To point #1, it's very common to not *need* anything else, that the entirely reason AIP were added.  It's so common to just have a setter and/or getter that it made sense to have a shorter syntax for just that, while still allowing the more verbose syntax when it makes sense.

    To #2, it takes less work to use an AIP and initialize the string to empty than to use a non-auto property, and it's still frequently either appropriate, or acceptable, to have it initialized to null.  AIP never *costs* you anything here.

    #3 is just completely wrong.

    As for the point about anonymous types, they don't use anonymous properties in the first place, they just use regular properties.  

    I use auto implemented properties on a daily basis, usually many times per day.  There is no reason to manually write out the property definitions if an auto implemented property meets your needs; you should only manually define the getter/setter when an auto property can't do what you need.

    I'm rather baffled that Adavesh is getting so many upvotes for a post that's complete nonesense and demonstrates no understanding of what auto-implemented properties actually are.

    • Edited by servy42 Thursday, December 13, 2012 6:37 PM
    Thursday, December 13, 2012 6:36 PM
  • Thanks Servy.. Yeah. That 3rd point is definitely non-sense. I don't know what was I thinking while writing that. Thanks Louis as well. Actually what happened was - I had put my code for review last day, thinking that I am the best coder in my team. And of course, I had AIPs in my code. The first review comment I recieved from my new Architect was, "What is the use of this AIP? It just looks similar to public member. Are you using this construct just because they are available?". I really didn't have a proper answer. I still tried to convince him but he stick to only question - "What if use public member directly instead of this type of Property, tell me the pro and cons." So, again, I didn't have proper answer.

    In my 3 years of .NET experience, I never had such embarrassing experience. Coincidentally, this night I saw this question (and you know, I thought he only has posted this question). And with the same mindset I wrote my answer and got screwed by you guys :) Anyways, that you guys. I am going to delete my post above..I know I will loose 3 votes though :


    Please mark this post as answer if it solved your problem. Happy Programming!

    Friday, December 14, 2012 3:50 AM
  • Thanks Servy.. Yeah. That 3rd point is definitely non-sense. I don't know what was I thinking while writing that. Thanks Louis as well. Actually what happened was - I had put my code for review last day, thinking that I am the best coder in my team. And of course, I had AIPs in my code. The first review comment I recieved from my new Architect was, "What is the use of this AIP? It just looks similar to public member. Are you using this construct just because they are available?". I really didn't have a proper answer. I still tried to convince him but he stick to only question - "What if use public member directly instead of this type of Property, tell me the pro and cons." So, again, I didn't have proper answer.

    In my 3 years of .NET experience, I never had such embarrassing experience. Coincidentally, this night I saw this question (and you know, I thought he only has posted this question). And with the same mindset I wrote my answer and got screwed by you guys :) Anyways, that you guys. I am going to delete my post above..I know I will loose 3 votes though :


    Please mark this post as answer if it solved your problem. Happy Programming!

    Keep in mind that in that context an auto-implemented property is just the same as a manually implemented property, the auto property just takes less typing.

    As to whether it's appropriate to use any property at all, that's an *entirely* different question, and would require more context.

    Friday, December 14, 2012 2:16 PM