tags:

views:

1520

answers:

2

How can I initialize a list containing generic objects whose types can be different?

For example, I have the following:

this.Wheres = new List<Where<>>();

As you know, <> is not valid syntax. However, sometimes the type passed to Where will be a string and sometimes it will be DateTime, etc. I tried using object as the initialized type, but that doesn't work either.

A: 
this.Wheres = new List<Object>();
Sergio
This will add (un)boxing and remove type safety.
lacop
How can you prevent that if the list can be composed of different object types??
Sergio
This is the right way to do what the OP asked. Yes, it's not type-safe. That's not the answer's fault.
Robert Rossney
+7  A: 

Well, you haven't really given enough context (what's SqlWhere?) but normally you'd use a type parameter:

public class Foo<T>
{
   private IList<T> wheres;

   public Foo()
   {
       wheres = new List<T>();
   }
}

If you want a single collection to contain multiple unrelated types of values, however, you will have to use List<object>

Jon Skeet
Thanks! And to answer your question, Where is a class in the query builder.
David Brown