tags:

views:

117

answers:

4
+2  Q: 

Generic Lists c#

Is the following at all possible in c#?

I have the following but the last line won't compile, am i missing something?

public static void BuildGeneric<T>(List<T> l)
{
    l = new List<T>();
    var anything = new object();
    l.Add(anything);
}

"The best overloaded method match for 'System.Collections.Generic.List.Add(T)' has some invalid arguments"

+5  A: 

No.

l can only hold objects of type T.
Your code tries to defeat the entire purpose of generics.

If you change anything to be of type T, it will work.
If you cast it to T, it will compile, but will throw an InvalidCastException at runtime unless it acutally is a T.

What are you trying to do?

SLaks
+12  A: 
public static void BuildGeneric<T>(List<T> l)
{
    l = new List<T>();
    var anything = new object();
    l.Add(anything);
}

should be this

public static void BuildGeneric<T>(out List<T> l)
{
    l = new List<T>();
    var anything = default(T);
    l.Add(anything);
}

Now you could do

BuildGeneric<object>(out l);

Since there is a discussion (comment) below about the default keyword, I thought I should include a link to it:

http://msdn.microsoft.com/en-us/library/xwth0h0d(VS.80).aspx

Kevin
Ohhh +1 for `default(T)` I've never seen that before.
Spencer Ruport
Let me just add (for the benefit of the questioner) that this will create a list with a null in it if T is a reference type. You could use new T() instead if you put the generic constraint `new()` on T, which ensures that T must have a default constructor. If T is a value type it doesn't matter as structs in C# always have a default constructor (and you can't define your own) `default(SomeReferenceType)`yields null, `default(SomeValueType)` default constructs a value type, equal to `new SomeValueType()`
Skurmedel
@Skurmedel, good point!
Kevin
Argh, typo and I can no longer edit my comment :)
Skurmedel
+3  A: 

You need to modify your function in this way:

public static void BuildGeneric<T>(ref List<T> l)
    where T : new()
{
    l = new List<T>();
    T anything = new T();
    l.Add(anything);
}
Nick
+1  A: 

To me it sounds like you want to create a list which contains any kinds of items. Correct? As already pointed out - this can't be done.

An appropriate approach to this would be to create a common interface for the kind of objects you want in the collection. Have all the classes you want in the collection implement this interface, and then you can have a list containing elements implementing this interface.

stiank81