I'm trying to learn C#, and am coming from Java. I've seen this in C#:
class A {
public string x { get; set; }
}
What do I do if I want to intercept the incoming value on the setter?
I'm trying to learn C#, and am coming from Java. I've seen this in C#:
class A {
public string x { get; set; }
}
What do I do if I want to intercept the incoming value on the setter?
This is just syntactic sugar for
private string x;
public string X
{
get { return this.x; }
set { this.x = value; }
}
which is effectively what the compiler really outputs for your code, though you can't access the field x
directly.
Always use this long form if you need to do anything beyond setting and retrieving the value from a field.
You can create a backing store:
private string _x;
public string x {
get {
return _x;
}
set {
// do something - you can even return, if you don't want the value to be stored
// this will store the value
_x = value;
// do something else
}
}
First you should make a private property that you will store the actual values in. In the get function just return that private property. In the set method you can use the value keyword to see the incoming value and do whatever you want before actually setting the private property;
public class A
{
private string xPrivate;
public string X {
get { return this.xPrivate; }
set { this.xPrivate = value; }}
}