maxp
maxp

Reputation: 25141

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"

Upvotes: 2

Views: 5680

Answers (4)

kemiller2002
kemiller2002

Reputation: 115420

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

Upvotes: 13

stiank81
stiank81

Reputation: 25686

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.

Upvotes: 1

Nick
Nick

Reputation: 5945

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);
}

Upvotes: 3

SLaks
SLaks

Reputation: 887215

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?

Upvotes: 7

Related Questions