I often find I want to write code something like this in C#, but I am uncomfortable with the identifier names:
public class Car
{
private Engine engine;
public Engine Engine
{
get
{
return engine;
}
set
{
engine = value;
}
}
public Car(Engine engine)
{
this.engine = engine;
}
}
Here we have four different things called "engine":
Engine
the class. Engine seems like a good, natural name.Engine
the public property. Seems silly to call it MyEngine or TheCarsEngine.engine
the private field backing the property. Some naming schemes will recommend m_engine
or _engine
, but others say that all prefixes should be avoided.engine
the parameter name on the constructor. I've seen naming schemes that recommend prefixing an underscore on all parameters, e.g., _engine
. I really dislike this, since the parameter is visible to callers via Intellisense.The particular things I don't like about the code as written are that:
this.engine = Engine;
It seems that each name is appropriate in isolation, but together they are bad. Something has to yield, but what? I prefer to change the private field, since it's not visible to users, so I'll usually end up with m_engine
, which solves some problems, but introduces a prefix and doesn't stop Intellisense from changing engine
to Engine
.
How would you rename these four items? Why?
(Note: I realise the property in this example could be an automatic property. I just didn't want to make the example overcomplicated.)
See also: Am I immoral for using a variable name that differs from its type only by case?
Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields. Properties are an extension of fields and are accessed using the same syntax.
A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.
The get method returns the value of the variable name . The set method assigns a value to the name variable. The value keyword represents the value we assign to the property. If you don't fully understand it, take a look at the example below.
Properties can be marked as public , private , protected , internal , protected internal , or private protected . These access modifiers define how users of the class can access the property. The get and set accessors for the same property may have different access modifiers.
In this case, I would name them exactly as they are in the example.
This is because the naming is clear as to what data each element holds and/or will be used for.
The only thing I would change for C#3 is to use an auto-property which would remove the local variable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With