oop - Should I assign class fields via property setter or not in C#? -
what correct way of doing this? property setter might contain more code acctual assignment. lets have following code:
class person { private string name; public person(string name) { this.name = name } public string name { get; set { if(string.empty.equals(value)) return; this.name = value; } } } is above code wrong since not assign via property?
- unless you've got reason otherwise, should use property
nameinstead of fieldname, in same class, ensure logic inget/setmethods used. - since explicitly specify
setimplementation, must explicitly specifygetimplementation example compile. - in cases, should use
string.isnullorempty, not other approachesstring.empty.equals(value)code. properties should behave in unsurprising ways. after run
person.name = "";, you'd expectnameproperty"", not before. if setting null or empty name not valid, should throw exception when passed such value.class person { private string name; public person(string name) { this.name = name; } public string name { { return this.name; } set { if(string.isnullorempty(value)) throw new argumentexception("name required", "value"); this.name = value; } } }
Comments
Post a Comment