Private Accessor in C# -
i'm little confused accessor's in c#. assumed done private accessor's:
private string m_name = { { return m_name; } // not sure if correct. maybe use 'this' set { m_name = value } // not sure if correct }
i'm not sure if code above valid. i've not used accessors in c#.
instead, documentation states this:
class employee { private string m_name; public string name { { return m_name; } protected set { m_name = value; } } }
why done, because perspective user can still access private m_name property via name. doesn't defeat point of private (or protected) properties?
in first example shouldn't compiler know private , create methods behind scenes (as believe @ compile time)?
your first example give stackoverflowexception, need either use separate member store data or use auto properties.
to answer question, reason done make property readonly outside of class, allow code running inside class still set property.
class employee { public employee(string name) { name = name; } private string m_name; public string name { { return m_name; } protected set { m_name = value; } } public void changename(string name) { name = name; } } public class ceo : employee { public ceo(string name) : base(name) { } public void voteout() { name = name + " (fired)"; } } static class mainclass { static void main(string[] args) { var employee = new employee("scott chamberlain"); console.writeline(employee.name) //displays scott chamberlain; //employee.name = "james jeffery"; //has complier error if uncommented because name not writeable mainclass, members of employee can write it. employee.changename("james jeffery"); console.writeline(employee.name) //displays james jeffery; } }
Comments
Post a Comment