SamFisher83
SamFisher83

Reputation: 3995

Is it possible to make a list of generics that return a specific data type?

class a {

}

class b<T>:a {
 public T foo;
}


List<a> foo2 = new List<a>();

b<int> foo3 = new b<int>();

foo3.foo = 4;

foo2.add(foo3);

now foo2[0].foo won't work since class a does not have that property. However I want to make it so the list can have a bunch of generic items.

Currently I am converting all the type to strings or a byte array. Is there a way to create a list of generic items that will return a specific type back?

Upvotes: 0

Views: 87

Answers (1)

Paolo Falabella
Paolo Falabella

Reputation: 25844

For a solution without type casts, you should take a look at the accepted answer to this question: Discriminated union in C#

The Union3 (or 4 or 5 or how many different types you need) type proposed by Juliet would allow you to have a list that accepts only the types you want:

    var l = new List<Union3<string, DateTime, int>>  {
            new Union3<string, DateTime, int>(DateTime.Now),
            new Union3<string, DateTime, int>(42),
            new Union3<string, DateTime, int>("test"),
            new Union3<string, DateTime, int>("one more test")
    };

        foreach (Union3<string, DateTime, int> union in l)
        {
            string value = union.Match(
                str => str,
                dt => dt.ToString("yyyy-MM-dd"),
                i => i.ToString());

            Console.WriteLine("Matched union with value '{0}'", value);
        }

See here for complete example: http://ideone.com/WZqhIb

Upvotes: 1

Related Questions