Suppose that I have class Foo and
class FooFrobber
{
private Foo _foo;
FooFrobber(Foo foo)
{
_foo = foo;
}
Frob()
{
_foo.FrobCount += 1;
}
}
It seems like _foo is a good name for a private field, but what if I want to make it an internal or protected variable? The convention (http://weblogs.asp.net/lhunt/archive/2004/08/17/CSharpCodingStandardsv113.aspx via Style guide for c#?) seems to be to use a StudlyCaps with no m_ or trailing _, which means that I will declare protected Foo Foo. This seems to work, but it seems a little bit odd to be shadowing a class name. The style guide says that all fields should be private, but that seems a bit excessive (but maybe that’s my inner python speaking). At any rate, it seems like you would have the same problem if we wanted to wrap _foo in a property.
Should I always come up with a different name for the field, as in MyFoo? Is it ok to leave this as it is, as the compiler doesn’t seem to mind?
It’s allowed and common practice to have fields/properties that share the same name as their type. First example that comes to mind from the FCL is
DispatcherObject.Dispatcher, which returns an instance of typeDispatcher.However, I personally prefer to avoid declaring fields as protected, and use properties instead. If you want to avoid the coding involved with declaring a backing field, you may use an auto-implemented property:
The advantage of using properties is that you can apply different access modifiers for the getter and the setter:
Edit: The advantage of using protected properties instead of protected fields is that they allow you to change their implementation – for example, to introduce value validation or change notification – without breaking external libraries that might access it.
Suppose, for example, that you want to extend your class to implement
INotifyPropertyChanged. If you were using a protected field, there would be no straightforward way of detecting when the value of the field is changed by a consuming assembly (unless you change the implementation of the external assembly as well). If you were using a protected property, you could simply alter its implementation without requiring any changes in consuming assemblies:Edit2: Several more advantages to using properties over fields are given in LBushkin’s answer.
Changing a field to a property does appear to break the ABI. I haven’t yet found it stated in an authoritative source (I didn’t spend too much time looking); however, per pst’s comment:
Per jstedfast’s answer: