I need to hold an object in class that is restricted to be either a string or a double. How to do it stylistically right? I came up with idea to create a enum with possible types and two methods for each type to set the field.
public class Operand
{
/// <summary> Possible types of operand </summary>
public enum TYPE
{
/// <summary> Number </summary>
Numeric,
/// <summary> Parameter </summary>
Parameter,
/// <summary> Invalid </summary>
None
}
/// <summary> Type of operand </summary>
public TYPE Type { private set; get; } = TYPE.None;
/// <summary> Value of operand: double or string </summary>
public object Value { private set; get; } = null;
/// <summary> Set the parametric operand </summary>
public void Set(string value)
{
Value = value;
Type = TYPE.Parameter;
}
/// <summary> Set the numeric operand </summary>
public void Set(double value)
{
Value = value;
Type = TYPE.Numeric;
}
}
You can set value with one method like this:
public void Set(object value)
{
if (value is String)
{
// Type string
}
else if (value is Double)
{
// type double
}
}
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