Carra
Carra

Reputation: 17964

List of generic objects

I have a ContextBase class like this:

public class ContextBase<T, TK> where T : IIdAble<TK>, new()
{

}

And a class containing a few ContextBases:

public static class Context
{
    private static ContextBase<Action, int> _actionContext;
    private static ContextBase<Customer, long> _customerContext;
}

Now, can I put these two ContextBases in one List? I need something like this in Context:

private static List<ContextBase<T,K>> _contexts;

I could just use an ArrayList but is it possible with generics?

Upvotes: 1

Views: 161

Answers (3)

Warrenn enslin
Warrenn enslin

Reputation: 1036

because ContextBase is defined as ContextBase<T, TK> where T : IIdAble<TK> it means that the compiler would see ContextBase<Action, int> and ContextBase<Customer, long> as seperate classes asking for a List<ContextBase<T,K>> is almost the equivalent of asking for a List of int, long it violates the intent of the generic list. What you could do instead is have a list of a class that both ContextBase<Action, int> and ContextBase<Customer, long> have in common in other words.

public class ContextBase<T, TK> : CommonClass where T : IIdAble<TK>, new(){...}

and then

private static List<CommonClass> _contexts = new List<CommonClass>{
  new ContextBase<Action, int>(), 
  new ContextBase<Customer, long>()
};

Upvotes: 1

Kendall Frey
Kendall Frey

Reputation: 44374

You won't be able to do this type-safely. You don't, however, need to go as far as the unsafety of ArrayList.

public class ContextBase<T, TK> : IContextBase where T : IIdAble<TK>, new()
                                  ^          ^

Make a non-generic interface that ContextBase implements, then use a List<IContextBase>.

Unfortunately, you'll still lose the ability to use generic members of ContextBase, but that's the minimum price you'll have to pay.

Upvotes: 1

Heinzi
Heinzi

Reputation: 172468

No, it's not possible. It's like asking whether you can store strings and ints in anything more specific than a List<object>.

Since object is the only common base class of ContextBase<Action, int> and ContextBase<Customer, long>, you can only use a List<object> to store both in the same list.

You can, however, make them implement a common (non-generic) interface IContextBase that contains all the functionality you need to perform on these list items, and have ContextBase<T, TK> implement IContextBase. Then you can use a List<IContextBase>.

Upvotes: 1

Related Questions