Reputation: 336
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;
}
}
Upvotes: 3
Views: 872
Reputation: 397
I propose the solution with two different fields for values. This way we avoid boxing and unboxing when the value is double. It's less laconic and requires manual check of Type field, but saves recources when double type is used
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;
public string StringValue { private set; get; }
public double DoubleValue { private set; get; }
/// <summary> Set the parametric operand </summary>
public void Set(string value)
{
StringValue = value;
Type = TYPE.Parameter;
}
/// <summary> Set the numeric operand </summary>
public void Set(double value)
{
DoubleValue = value;
Type = TYPE.Numeric;
}
}
Upvotes: 0
Reputation: 410
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
}
}
Upvotes: 1