Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Restrict object to several types

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;
    }
}
like image 453
Perotto Avatar asked May 19 '26 08:05

Perotto


1 Answers

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
    }
}
like image 60
mustafa Avatar answered May 21 '26 23:05

mustafa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!