This might be a bit of an anti-pattern, but it is possible for a property on a C# class to accept multiple values?
For example, say I have an Public int property and I always want it to return an int, but I would like to be able to have the property set by assigning a decimal, an integer or some other data type. So my question is if it possible for properties to accept multiple values?
I think what you mean to ask is: How does implicit and explicit casting work for int
and decimal
?
You are asking about implicit casting which automatically coverts one object to another defined type. You will not be able to do this for an int
and decimal
because they are already defined in the framework and you are not able to reduce the scope of the decimal
by casting it to an int
. But if you were using that as an example for actual objects that you created you can use the implicit link above, to learn more about how this works and how to implement it.
But you can always use the convert method to convert them to the right type;
public int MyProperty { get; set; }
...
obj.MyProperty = Convert.ToInt32(32.0M);
obj.MyProperty = Convert.ToInt32(40.222D);
obj.MyProperty = Convert.ToInt32("42");
Edit: This method can't be used since the op is specifically bound to properties.
I do not believe this is possible with the robustness that you describe. In this case you would likely be better off using an overloaded method (polymorphism).
This is what is typically known as a setter (or mutator) and you can overload the method to accept multiple different types of parameters. Each will perform differently if you wish. The way I have them set up might not be syntactically correct but that is the general idea you're looking for I believe.
public class MyClass {
private Int32 mySomeValue;
public void setSomeValue(Double value) { this.mySomeValue = Convert.ToInt32(value); }
public void setSomeValue(Int32 value) { this.mySomeValue = value; }
}
No. A property has a single value. You can assign anything to it that could be assigned to a variable of the same type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With