C# properties: how to use custom set property without private field?
I want to do this:
public Name
{
get;
set
{
dosomething();
??? = value
}
}
Is it possible to use the auto-generated private field?
Or is it required that I implement it this way:p开发者_开发问答rivate string name;
public string Name
{
get
{
return name;
}
set
{
dosomething();
name = value
}
}
Once you want to do anything custom in either the getter or the setter you cannot use auto properties anymore.
You can try something like this:
public string Name { get; private set; }
public void SetName(string value)
{
DoSomething();
this.Name = value;
}
As of C# 7, you could use expression body definitions for the property's get
and set
accessors.
See more here
private string _name;
public string Name
{
get => _name;
set
{
DoSomething();
_name = value;
}
}
This is not possible. Either auto implemented properties or custom code.
It is required that you implement it fully given your scenario. Both get
and set
must be either auto-implemented or fully implemented together, not a combination of the two.
精彩评论