27 March 2011

Compatibility between Public fields and properties

If your class wants to expose some data, you have two possibilities:
  1. Use a public field
    public class Person { public string Name; }
  2. Use a public property that is backed by a private field
    public class Person { private string name; public string Name { get { return name; } set { name = value; } } }
The general advise is that you should not have any public fields, thus you should always use properties. However some people suggest that you can start out with a public field and that you can easily change it into a property when the need arises.
But this is not true for two reasons:
  1. A public field and a property are binary incompatible. When you change your public field into a property you will have to recompile all the clients of your class.
  2. A public field and a propery are also incompatible at source-code level. A public field can be passed as a ref- or out-parameter while a property cannot. So when you change your public field into a property, you may have to actually change the client code.
So my advise: unless you have *very* strict performance considerations always use properties.
Regarding performance, keep in mind that a simple propery that is not marked as virtual (or that is part of a sealed class) will likely be inlined by the compiler so there shouldn't be any performance impact at all (in release-builds).

No comments:

Post a Comment

Your comments, Feedbacks and Suggestions are very much valuable to me :)

Things are upgraded

My Dear readers, I am really thankful for being supportive all these years. This site was the first blog site I ever created in my life...