开发者

What is the syntax in C# for creating setters and getters?

开发者 https://www.devze.com 2022-12-29 22:09 出处:网络
I\'m familiar with this new syntax sugar: public string Name { get; set; } But what if I was the setter of that variable to have some sort of checking. For example, I want to convert the entire str

I'm familiar with this new syntax sugar:

public string Name { get; set; }

But what if I was the setter of that variable to have some sort of checking. For example, I want to convert the entire string that is supposed to be Set to all lowercases.

开发者_Python百科
public string Name
{
   get;
   set 
   {
      ????
   }
}


You will need a backing field for both the getter and setter (you can't have a partially automatic property):

private string name;
public string Name
{
   get
   {
     return name;
   }
   set 
   {
     // do validation or other stuff
     name = value.ToLower();
   }
}


You can't define a partially-automatic property. You would have to do things the old fashioned way: define backing field and implement the getter and setter logic yourself.


private string _name;

public string Name
{
   get {return _name;}
   set 
   {
     _name = value.ToLower();
   }
}


Then you cannot use the auto generated get/set feature:

string _name;

public string Name {
    set { _name = value.ToLower(); }
    set { return _name; }
}


public string Name { get; set; } These are called Auto Implemented Properties. In C# 3 and later you can use this syntax for property. But if you want to do any operation on the value before setting, then this is not helpful . One more disadvantage is ,you have to use both set and get,you can't declare only getter. Alternate is to make the setter private. In your case, you have to use the older version of properties.

private string _name;
public string Name
{
   get {return _name;}
   set 
   {
      //do any operation
     _name = value.ToLower();
   }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号