If your class wants to expose some data, you have two possibilities:
- Use a public fieldpublic class Person { public string Name; }
- Use a public property that is backed by a private fieldpublic class Person { private string name; public string Name { get { return name; } set { name = value; } } }
But this is not true for two reasons:
- 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.
- 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.
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 :)