Private Variables vs Properties in C# -


i teaching myself c# , curious need declaring private member variables accessed public properties. textbook i'm using says sake of encapsulation, why need private variables begin if properties can changed depending on 'get' or 'set' functions? here's example:

namespace practice {     struct person     {         private int id;         private string name;          public int id { {return id;} set {id = value;} }         public string name { get; set; }         public int age { get; set; }     }     class program     {          static void main(string[] args)         {              person person = new person();             person.id = 548;             person.name = "dude";              console.writeline(person.name);         }     } } 

so name , id operate exact same way, what's purpose of declaring private int id , private string name?

in case, since not doing backing field (private field), don't need it. can work auto properties (but, remember, auto properties use backing field in background).

having backing field useful if doing operation it, example, if want verify id should greater 100, can

public int id {         {         return id;     }     set     {         if(id <= 100) throw new exception("invalid id provided");         id = value;     } } 

if try apply same logic on property, instead of backing field, will/could run infinite recursion.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -