Reputation:
One of the nice features of .net is class Properties - wrapping gettter and setter of class field (which is private, but accessor methods are ussualy public). From outside of a class this Property looks as one field and does not flood intellisense with nomber of getters and setters.
Usual syntax is
private bool _isReadOnly;
public bool IsReadOnly
{
get { return _isReadOnly; }
set { _isReadOnly = value; }
}
or for implicit declaration it is
public bool IsReadOnly
{
get;
set;
}
This is very nice, both accessors can have even different access modifiers, eg. private setter.
My question is: does .NET support setters or getters with parameters? Like to have setter with two parameters - for example - one is value to set and other is bool which indicates something like "notify listeners about change" or "do not overwrite old value if newer value fails check" or something like that. Parameter for getter could be some option to format output or whether returned value should be clone of old etc.
Thank you. I do dot need it for any particular goal to achieve, so no need to post workarounds, i just wonder if there is something like this in .net Property.
Upvotes: 5
Views: 16184
Reputation: 1490
Nope; however, you can make the get/set accessors have some nice check logic. If you have another field that you set (outside of the get/set) method, you can check against that field during your 'set' update to branch your logic based on a condition.
private bool positiveOnly;
private int _myNum;
public int MyNum
{
get {return _myNum;}
set
{
// use old if positive only and value less than 0
_myNum = (positiveOnly && value < 0) ? _myNum : value;
}
}
public void MyMethod()
{
positiveOnly = true;
MyNum = Convert.ToInt32(txtMyTextBox.Text);
}
Upvotes: 0
Reputation: 11214
No - a property is simply used to retrieve or set a value. For your examples, you'd need to use a method.
Upvotes: 2