C# Use field or property inside the same class -


when referring value inside class (from within same class), should use field or property can accessed other classes?

for example, way should referring variable in class, , why?

public static class debug {     private static int _numberofevents = 1;      public static int numberofevents     {         {         return _numberofevents;     }     set     {         _numberofevents = value;     } }  public static void logevent(string event) {     //this way?     console.writeline("event {0}: " + event, _numberofevents);     _numberofevents++;      //or way?     console.writeline("event {0}: " + event, numberofevents);     numberofevents++; } 

}

thanks

when simple property this, consider replacing "automatic" property, this:

public static int numberofevents {get;set;} 

with properties simple, not matter way access them: although accessing backing variable may seem little faster, optimizer take care of optimizing out function call, making both accesses equally fast.

when property more complex, example, when has additional validations and/or triggers events, decision becomes more complex: need decide if want have effects associated accessing property, or if wish avoid them. make decision based on want happen.


Comments

Popular posts from this blog

c# - Send Image in Json : 400 Bad request -

jquery - Fancybox - apply a function to several elements -

An easy way to program an Android keyboard layout app -