none
what benefit public automatic properties provide us as compared to public fields? RRS feed

  • Question

  • in C# when we create public properties to get and set the values of private members of a class, we preserve encapsulation as the logic in the set method prevents object fields to get assigned unwanted values... and also simplifies our code.... that's all fine.

    but when we do not have business rules for object fields we define them as public automatic properties which at the back end creates necessary variables ..... we still are able to use natural looking syntax outside the class to get, set these member's values.... 

    what benefit we get in terms of encapsulation in the case of public automatic properties that we wouldnt have if class fields are not exposed using automatic properties but declared directly as public....???

    at the end both does the same work ??? can anyone clarify plz............. 

    thanks to all in advance...


    farooq.hnf


    • Edited by farooq.hnf Wednesday, November 20, 2013 4:35 AM in the previous version of this question i mistakenly wrote public members everywhere i had to write public fields...
    Tuesday, November 19, 2013 1:01 PM

Answers

  • While they are used similary, Properties and Public Fields are decidedly not the same.

    Fields are jsut varriables.

    Properties are Syntax Sugar for get and set functions that look like this:

    private int _X;
    
    int getValueX(){
      return _X;
    }
    
    void setValueX(int Value){
      _X=Value;
    }
    
    //Wich would be called like this
    setValueX(getValueX()+1);
    //It's a lot more syntax then X++;

    Always keep in mind that Properties are two Functions.

    The advantages of Properties over fields:

    You can make non-symetric accessors (private set or private get; or no set/get at all), effectively creating readonly properties.

    As Properties are Functions they can be defined as part of a Interface (Fields cannot).

    As Properties are Functions they can be overriden, hidden and have all the other Polymorphy applied to it.

    (disadvantage)Properties cannot be be used for "ref" or "out" parameters. You have to use code like this instead:

    //This will not compile
    Int32.TryParse(input, out X);
    
    int temp = X;
    TryParse(input, out temp);
    X = temp;

    Thus it is important to directly start with Properties and not change Fields to Proeprties later. Just because there is no Business Logic now does not means there never will be a Business Logic in a later version of the class or in a derived class.

    On the other hand, a empty Property accessors will not cost performance.

    Calling a Function always has a small price for Performance. If you have a accessors like these:

    //Autoimplemented Proeprty
    public int X { get; set; }
    
    
    private int _Y;
    
    public int Y{
      get { return _Y; }
      set { _Y=Value; }
    }

    Normal logic would dictate that those are slightly slower then just writing Fields. However the Just-in-time compiler will see those functions do nothing but give/set a value. So it will inline them, removing any overhead.

    If you later changed them to have business logic (or they get overwritten to have them), the JiT will see it and not touch them.

    In short:

    No disadvantages (aside from the minor propblem with ref/out parameters).

    A lot of possible advantages in the future.

    The fact that you will be hard pressed to find any class in the .NET Framework who has any public Fields (asside from Constant Fields like Int32.MaxValue) should tell you that using them over Fields is the right path.


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.


    • Edited by Christopher84 Tuesday, November 19, 2013 2:11 PM
    • Marked as answer by farooq.hnf Friday, November 22, 2013 7:35 AM
    Tuesday, November 19, 2013 2:09 PM

All replies

  • This can easily get into a philosophical debate. However, these are my personal opinions.

    • I use automatic properties to avoid breaking changes if I in the future want to add validation or some kind of logic to it. (Yes, this violates the "KISS-principle", but I can live with that).
    • I've gotten used to it, so at this point I find it cleaner.
    • I can debug property sets/gets, which can actually be quite handy sometimes.

    Other things mentioned when this discussion comes up is that data binding only works for properties and reflection is easier with properties than fields.

    Tuesday, November 19, 2013 1:57 PM
  • While they are used similary, Properties and Public Fields are decidedly not the same.

    Fields are jsut varriables.

    Properties are Syntax Sugar for get and set functions that look like this:

    private int _X;
    
    int getValueX(){
      return _X;
    }
    
    void setValueX(int Value){
      _X=Value;
    }
    
    //Wich would be called like this
    setValueX(getValueX()+1);
    //It's a lot more syntax then X++;

    Always keep in mind that Properties are two Functions.

    The advantages of Properties over fields:

    You can make non-symetric accessors (private set or private get; or no set/get at all), effectively creating readonly properties.

    As Properties are Functions they can be defined as part of a Interface (Fields cannot).

    As Properties are Functions they can be overriden, hidden and have all the other Polymorphy applied to it.

    (disadvantage)Properties cannot be be used for "ref" or "out" parameters. You have to use code like this instead:

    //This will not compile
    Int32.TryParse(input, out X);
    
    int temp = X;
    TryParse(input, out temp);
    X = temp;

    Thus it is important to directly start with Properties and not change Fields to Proeprties later. Just because there is no Business Logic now does not means there never will be a Business Logic in a later version of the class or in a derived class.

    On the other hand, a empty Property accessors will not cost performance.

    Calling a Function always has a small price for Performance. If you have a accessors like these:

    //Autoimplemented Proeprty
    public int X { get; set; }
    
    
    private int _Y;
    
    public int Y{
      get { return _Y; }
      set { _Y=Value; }
    }

    Normal logic would dictate that those are slightly slower then just writing Fields. However the Just-in-time compiler will see those functions do nothing but give/set a value. So it will inline them, removing any overhead.

    If you later changed them to have business logic (or they get overwritten to have them), the JiT will see it and not touch them.

    In short:

    No disadvantages (aside from the minor propblem with ref/out parameters).

    A lot of possible advantages in the future.

    The fact that you will be hard pressed to find any class in the .NET Framework who has any public Fields (asside from Constant Fields like Int32.MaxValue) should tell you that using them over Fields is the right path.


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2 Please mark post as helpfull and answers respectively.


    • Edited by Christopher84 Tuesday, November 19, 2013 2:11 PM
    • Marked as answer by farooq.hnf Friday, November 22, 2013 7:35 AM
    Tuesday, November 19, 2013 2:09 PM
  • Speaking as more of a hobby C# programmer than professional programmer, properties make more sense to me than declaring a method for getting and setting. When I transitioned from VB to C#, I really got a better understanding of what it meant to be a method.. you may or may not know, but in VB, if you are calling a method without any parameters and you omit the empty parenthesis after, the compiler will process the code anyway. In C#, it's a no-go.

    Once I began to better understand what it meant to be a method vs a property, it began to feel to me like overkill declaring a method when all I really wanted to do was present class variables or accept values from the outside. There's just something elegant to me about var MyInt = MyClass.MyInteger; as opposed to var MyInt = MyClass.GetMyInteger();.

    Another area where it makes more sense is managing the amount of externally available methods and properties. Say you have a class that contains the DateTime a certain process started. If you were to create methods to get and set this value, you would need two separate functions, perhaps one named SetStartTime() and one named GetStartTime(). With a property, you can include the get and set code in a single property called StartTime. Now it's true, something as trivial as a start time may be able to only have a getter method, or maybe you don't want to expose the start time to be set externally.. but you get the point. If you can consolidate each get and set into a single property, there's less to maintain and less to look at if you rely on (or even occasionally use) Intellisense.

    Professionally, I can't say if I'm qualified enough to say if one is right or wrong.. it just feels more elegant, the code looks a lot cleaner, and it simplifies naming conventions when using properties over methods. Personally, my thought is it's more important is that you are consistent. If your team uses properties, try to keep your code base consistent and do as they do. If your team uses methods, again, strive for consistency and use methods. If you only have yourself to worry about do what works for you and keep it consistent.



    Tuesday, November 19, 2013 2:33 PM
  • Based upon the question it sounds like what you want to know is the difference between a "normal" public property and an auto property.

    //Normal property
    private string _someField;
    public string SomeField
    {
       get { return _someField; }
       set { _someField = value; }
    }
    vs
    public string SomeField { get; set; }

    The answer is there is no semantic difference.  In both cases you are exposing a public property backed by a private field.  You can use either syntax and the rest of the world will not be impacted.  You can even switch back and forth.  There is no semantic difference in the generated code.

    The whole reason auto properties exist is because normal properties require a lot more typing and are almost always boilerplate code.  As such if you find yourself creating the boilerplate code then use an auto property instead and let the compiler generate it for you. 

    There are cases where auto properties will not work well. In these cases it makes sense to use a normal property instead. 

    • Custom get/set logic on the property.
    • Non-default field initialization.  With an auto property the field is default initialized.  If you want to use another value then you have to implement a constructor (ctor).  In general you should prefer normal property init over an auto property that requires a ctor (unless you already have a ctor defined). 
    • Set once properties.  It is generally considered good practice to mark properties that are only set at init time as readonly.  You have to use a normal property for this.

    In general I recommend using auto properties when possible as it cuts down on the code you have to write and maintain.  Use a normal property in any case where an auto property won't work well.  It is not a breaking change to switch between the 2 implementations as it is completely hidden inside the class implementation.

    Michael Taylor
    http://msmvps.com/blogs/p3net

    Tuesday, November 19, 2013 3:50 PM
    Moderator
  • Christopher84 you said:

    1) You can make non-symetric accessors (private set or private get; or no set/get at all), effectively creating readonly properties.

    ->automatic properties cannot be read-only or write-only

    2) they can be a part of an interface and also can be overridden...... thats a plus

    3) they can have business logic in future..... thats also a plus



    farooq.hnf

    Tuesday, November 19, 2013 4:41 PM
  • chipmunkofdoom2 you have completely missunderstood my question bro.... maybe u have to take a look on "automatic properties"....

    farooq.hnf

    Tuesday, November 19, 2013 4:42 PM
  • dear Michael Taylor ... the question was not what u understoodo bro... the question was about the difference bw public "automatic properties" and public fields..... 

    plz have a look again

    in C# when we create public properties to get and set the values of private members of a class, we preserve encapsulation as the logic in the set method prevents object members to get assigned unwanted values... and also simplifies our code.... that's all fine.

    but when we do not have business rules for object members we define them as public automatic properties which at the back end creates necessary variables ..... we still are able to use natural looking syntax outside the class to get, set these member's values.... 

    what benefit we get in terms of encapsulation in the case of public automatic properties that we wouldnt have if class members are not declared using automatic properties but declared directly as public....???

    at the end both does the same work ??? 



    farooq.hnf

    Tuesday, November 19, 2013 4:46 PM
  • Your terminology is incorrect then.  Public member != public field.  A public member is any member of a type that is public.  This includes properties, methods, events and fields.  Nowhere in your question did I find field mentioned so I read your question as public property vs public automatic property (which you did mention).  Sorry for the confusion.  Please update your question and title to clarify that you are referring to public fields vs. public property (automatic isn't relevant) so others won't be confused as well.
    Tuesday, November 19, 2013 6:33 PM
    Moderator
  • One other advantage of a public property with a private DependencyProperty as a backing store is the ability to Bind in the Designer!  This may not seem important until you decide to bind everything seen in a UserControl or even a class library where you re-use code.  And don't forget this same design allows you to create Data Sources, which when done correctly allow you to drag a data source onto the designer and the designer creates all the fileds as either a DataGrid or the equivalent of a form with all the correct controls.  It takes about 2 mintues to create a very complex Datagrid or Data Form from scratch when using the designer instead of doing it manually.

    JP Cowboy Coders Unite!

    Tuesday, November 19, 2013 7:44 PM
  • my confessions CoolDadTx...... i know the difference between fields and members..... that was by mistake....

    farooq.hnf

    Wednesday, November 20, 2013 4:32 AM