tags:

views:

124

answers:

5

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.

public string Name
{
   get;
   set 
   {
      ????
   }
}
+10  A: 

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();
   }
}
Oded
+4  A: 

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.

LBushkin
+3  A: 
private string _name;

public string Name
{
   get {return _name;}
   set 
   {
     _name = value.ToLower();
   }
}
Barry
_There _are _guidelines _for _this - _don't _use _underscores.
Callum Rogers
@Callum Rogers - Ahahahaaha.. In an otherwise crappy morning, this brought a smile to my face.
Jordan S. Jones
+1  A: 

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

string _name;

public string Name {
    set { _name = value.ToLower(); }
    set { return _name; }
}
Ade Miller
A: 

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();
   }
}
freak