Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a C# property accept multiple values?

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?

like image 757
lomaxx Avatar asked Apr 14 '09 01:04

lomaxx


3 Answers

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");
like image 153
Nick Berardi Avatar answered Nov 19 '22 11:11

Nick Berardi


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; }
}
like image 30
Joe Phillips Avatar answered Nov 19 '22 10:11

Joe Phillips


No. A property has a single value. You can assign anything to it that could be assigned to a variable of the same type.

like image 1
John Saunders Avatar answered Nov 19 '22 11:11

John Saunders