c# - How can I access the backing variable of an auto-implemented property? -


in past declared properties this:

public class myclass {     private int _age;      public int age     {           get{ return _age;  }           set{ _age = value; }     } } 

now can do:

public class myclass {     public int age {get; set;}  } 

my question is, how can access private variable created automatically using notation?

i rather access private variable , not public accessor 'age'. there default notation access private variable, or not possible?

the aim of new automatic properties reduce amount of boilerplate code need write when have simple property doesn't need special logic in or set.

if want access private member these properties use, that's few reasons:

  • you need more simple get/set - in case, should avoid using automatic properties member.
  • you want avoid performance hit of going through or set , use member directly - in case, i'd surprised if there performance hit. simple get/set members very easy inline, , in (admittedly limited) testing haven't found difference between using automatic properties , accessing member directly.
  • you want have public read access (i.e. 'get') , class write member directly - in case, can use private set in automatic property. i.e.

    public class myclass {     public int age {get; private set;}  }

this covers reasons wanting directly backing field used automatic properties.


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -