Difference between these two accessor/getter/setter methods?
Whats the difference now between doing this:
public string Title { get; set; }
and this:
public string Title;
Back in the day people always said use accessor methods with private variables called by the public accessor, now that .net has made get; set; statements so simplified that they look almost the same without the private vari开发者_JAVA百科able as just using a public only variable, so whats the point and difference?
I have an article on this: Why properties matter.
In short: properties are part of an API. Fields are part of an implementation. Don't expose your implementation to the world. You can change an automatically implemented property to have more behaviour (maybe logging, for example) in a source and binary compatible way. You can't do that with a field.
The first one
public string Title { get; set; }
is a property (Which is in fact a function).
The second one
public string Title;
Is a field.
It is good to use properties to hide the implementation (Encapsulation).
In the second case, you can't modify the implementation of the accessor (because is not an accessor) without recompiling the dependent assemblies.
精彩评论