Reputation: 6170
When referring to a value inside a class (from within the same class), should you use the field or the property that can be accessed from other classes?
For example, which way should I be referring to a variable in my class, and why?
public static class Debug
{
private static int _NumberOfEvents = 1;
public static int NumberOfEvents
{
get
{
return _NumberOfEvents;
}
set
{
_NumberOfEvents = value;
}
}
public static void LogEvent(string Event)
{
//This way?
Console.WriteLine("Event {0}: " + Event, _NumberOfEvents);
_NumberOfEvents++;
//Or this way?
Console.WriteLine("Event {0}: " + Event, NumberOfEvents);
NumberOfEvents++;
}
}
Thanks
Upvotes: 8
Views: 5868
Reputation: 726469
When it is a simple property like this, consider replacing it with an "automatic" property, like this:
public static int NumberOfEvents {get;set;}
With properties this simple, it does not matter which way you access them: although accessing backing variable may seem like a little faster, the optimizer will take care of optimizing out the function call, making both accesses equally fast.
When the property is more complex, for example, when it has additional validations and/or triggers events, the decision becomes more complex: you need to decide if you want to have the effects associated with accessing the property, or if you wish to avoid them. Then you make a decision based on what you want to happen.
Upvotes: 5
Reputation: 65049
There is probably no difference in the end, since the JITter will no doubt inline the function call that is generated when using the property.. into a direct field access.
Personally (and in teams I have been in, including the current one), we use the field and leave properties for access outside the class.. unless they are automatic properties (which, surprisingly enough.. happens rarely for us) or they contain logic.
Upvotes: 3