C # Use field or property inside one class

When you refer to a value inside a class (from one class), should you use a field or property that can be accessed from other classes?

For example, how should I refer 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

+6
source share
2 answers

When this is a simple property like this, consider replacing it with an β€œautomatically” property, for example:

 public static int NumberOfEvents {get;set;} 

With the simplest properties, it doesn't matter how you access them: although access to the backup variable may seem a little faster, the optimizer will take care of optimizing the function call, making both accesses equally fast.

When a property is more complex, for example, when it has additional checks and / or trigger events, the solution becomes more complex: you need to decide whether you want to have effects associated with accessing the property, or if you want to avoid them. Then you make a decision based on what you want.

+4
source

In the end, there is probably no difference, since the JITter will no doubt have a built-in function call that is generated when using the .. property in direct access to the fields.

Personally (and in the teams that I was in, including the current one), we use the field and leave the properties for access outside the class .. if they are not automatic properties (which, surprisingly, rarely happens to us) or they contain logic .

+1
source

Source: https://habr.com/ru/post/951855/


All Articles