In C#, how do you mix a default get with an explicit set?
-
20-06-2021 - |
Question
I want to do something like this:
class Foo
{
bool Property
{
get;
set
{
notifySomethingOfTheChange();
// What should I put here to set the value?
}
}
}
Is there anything I can put there to set the value? Or will I have to explicitly define the get
and add another field to the class?
Solution
You either have a default property, with compiler-generated backing field and getter and/or setter body, or a custom property.
Once you define your own setter, there is no compiler-generated backing field. You have to make one yourself, and define the getter body also.
OTHER TIPS
There is no way.
You can either have both setter and getter auto-implemented
bool Property { get; set; }
Or implement both manually
bool Property { get { return _prop; } set { _prop = value; } }
No this is the case where auto-properties are not the best fit, and therefore the point at which you go to proper implemented properties:
class Foo
{
private bool property;
public bool Property
{
get
{
return this.property;
}
set
{
notifySomethingOfTheChange();
this.property = value
}
}
}
In many cases you can use the "Auto Property" feature e.g. public int Age { get; set; } = 43;
This is a good reference http://www.informit.com/articles/article.aspx?p=2416187
Naji K.