Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing non type safe with type safe generic method

Im looking for a way to replace the following:

public class NonTypeSafe
{
    private List<object> contents = new List<object>();
    public List<object> Contents {get { return contents; }};

    public NonTypeSafe(params object[] arguments)
    {
        foreach(object arg in arguments)
        {
            contents.Add(arg);
        }
    }
}

with something that is typesafe. The aim is to have an object into which i can add numerous objects of varying types. At present, checks have to be made when retrieving the objects to determine whether or not they are of the correct type / in the correct order.

At present i have the following:

public class TypeSafe<T1>
  {
    protected List<object> ArgList = new List<object>();

    private readonly T1 arg1;

    public TypeSafe(T1 arg1)
    {
      ArgList.Add(arg1);
      this.arg1 = arg1;
    }

    public T1 Arg1
    {
      get { return (T1) ArgList[ArgList.IndexOf(arg1)]; }
    }
  }



  public class TypeSafe<T1, T2> : TypeSafe<T1>
  {

    private readonly T2 arg2;

    public TypeSafe(T1 arg1, T2 arg2) : base(arg1)
    {
      ArgList.Add(arg2);
      this.arg2 = arg2;
    }

    public T2 Arg2
    {
      get { return (T2) ArgList[ArgList.IndexOf(arg2)]; }
    }
  }

And so on, adding new classes up to largest number parameters i would reasonably expect. Is there a better way to achieve this?

like image 879
richzilla Avatar asked Jul 06 '26 00:07

richzilla


1 Answers

Are you re-inventing System.Tuple?

A tuple is a data structure that has a specific number and sequence of elements. An example of a tuple is a data structure with three elements (known as a 3-tuple or triple) that is used to store an identifier such as a person's name in the first element, a year in the second element, and the person's income for that year in the third element.

like image 73
Damien_The_Unbeliever Avatar answered Jul 08 '26 13:07

Damien_The_Unbeliever



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!