Coding style and performance of properties
If I have a property in a class defined as follows:
private int mSomeNumber;
public int SomeNumber
{
get
{
return mSomeNumber;
}
}
and inside the same class, I am curious if people use the member variable, or if you use the property. For example:
public void DoSom开发者_JAVA技巧ething()
{
if(mSomeNumber == 0) // This way?
//if(SomeNumber == 0) // Or this way?
{
// Do something
}
}
I'm thinking that using the member variable directly might save a call, but I'm wondering if the property will be compiled to the same thing. Does anyone know if it is or what the "standard" might be?
You should use the property, unless you have a specific requirement for a workaround (example as per Henk's answer).
That way you can alter the functionality in the property getter without changing your calling code. For example, your getter might format the value for a prettier return value, or increment it by a constant, or if it is just wrapping up state from else where (in a nested object), etc.
These days, we just do:
public int SomeNumber
{
get;
private set;
}
So we don't have to bother declaring a private member field.
Declaring a member field and accessing it directly might save a (probably optimized) property call, but it also misses whatever checks and balances the property was designed to offer.
The difference, if any, is going to be very small. So approaching it from a 'performance' angle is wrong. If you did use this member so much it could matter, you probably should write it entirely different.
So the main criterion is readability and reliability. That means using the property and use any (future) business logic involved.
Only in rare situations would you use the backing field (like avoiding a validation rule or change notification).
And because that is rare it means we will usually do without a backing field at all, like in @Frederic's answer.
Using properties considered a best practice and is a standard thing for .net and C# world in general. This has the same benefits as usage of properties instead of fields in public contracts.
What benefits you recieve is described by Jon Skeet in his article: Why Properties Matter.
It is unlikley to cause any differences for performance since this properties will be almost always inlined by JIT.
There is also absolutely no difference between declaring backing field yourself as in original case vs. using automatic properties like in Frédéric's reply. Both cases have backing field (hidden in automatic case).
Read other asnwers for benifits of properties.
精彩评论