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?

  1. unless you've got reason otherwise, should use property name instead of field name, in same class, ensure logic in get/set methods used.
  2. since explicitly specify set implementation, must explicitly specify get implementation example compile.
  3. in cases, should use string.isnullorempty, not other approaches string.empty.equals(value) code.
  4. properties should behave in unsurprising ways. after run person.name = "";, you'd expect name property "", 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

Popular posts from this blog

matlab - Deleting rows with specific rules -

jquery - How would i go about shortening this code? And to cancel the previous click on click of new section? -