Let’s say I have a class with a public property inside, like this:
class Data
{
public int Property { get; set; }
}
Now, for some reason, I would want to pass a string to this property. I could convert the string to an Int32 before passing it but being lazy is easier. Is it possible to change the setter so that the conversion is automatically done ? As in:
if (value is string) Property = Int32.Parse(value);
Of course, this example doesn’t work. VS throws an error plus a warning about how value will never be string.
EDIT: yep, I know this is a bad idea. This is simply curiosity.
It’s not possible to change the setter in this manner. The setter of a property in C# must have the same type as the property itself. There is no way to insert a static conversion from any other type as a function of the setter.