C# Use field or property inside the same class

c#

Solution

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.

Problem

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

Original source

Related problems