Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Class Polymorphisim

If I have the following:

public abstract class Parameter<T>  
{
    protected T value;

    public virtual T Value
    {
        get { return value; }
        set { this.value = value; }
    }

    protected Parameter(T startingValue)
    {
        value = startingValue;
    }
}

public class FloatParameter : Parameter<float> 
{
    public FloatParameter(float startingValue) : base(startingValue){}
}

public class IntParameter : Parameter<int> 
{
    public override int Value
    {
        get { return value; }
        set { this.value = value > 100 ? 100 : value; }
    }

    public IntParameter(int startingValue) : base (startingValue) {}
}

Is there any way to create some List<Parameter> that can contain any of the derived types? For example, something like:

// no type specified in Parameter
List<Parameter> storedParameters = new List<Parameter>(); 
storedParameters.Add(new FloatParameter(2f));
storedParameters.Add(new IntParameter(7));

foreach(Parameter p in storedParameters)
{
    DoSomethingWithValue(p.Value);
}

Or, alternatively, if this implementation is flawed, is there a better way to do this? What I have here feels slightly naive.

like image 882
Danny Herbert Avatar asked Jun 18 '26 09:06

Danny Herbert


1 Answers

The only way I see to manage such case is to have and Interface that you use to manage the generic types, something like this should work:

public interface IParameter
{
    void DoSomething();
}

public abstract class Parameter<T>
{
    protected T value;

    public T Value
    {
        get { return value; }
        set { this.value = value; }
    }

    protected Parameter(T startingValue)
    {
        value = startingValue;
    }
}

public class FloatParameter : Parameter<float>, IParameter
{
    public FloatParameter(float startingValue) : base(startingValue) { }
    public void DoSomething()
    {
        Console.WriteLine(value);
    }
}

public class IntParameter : Parameter<int>, IParameter
{
    public IntParameter(int startingValue) : base(startingValue) { }

    public void DoSomething()
    {
        Console.WriteLine(value);
    }
}

Ont his case you would be able to create a List of the Interface IParameter and add there specific instances:

 var list = new List<IParameter>();
 list.Add(new FloatParameter(1F));
 list.Add(new IntParameter(1));

 foreach (var item in list)
 {
      item.DoSomething();
 }
like image 51
JavierFromMadrid Avatar answered Jun 20 '26 21:06

JavierFromMadrid