Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I create a List<Class<T>>?

Tags:

c#

.net

generics

I have a class

public class Setting<T>
{
    public string name { get; set; }

    public T value { get; set; }
}

now I want to create an IList<Setting<T>> but with different types of Setting<T>'s T in it, I want e.G.

List<Setting<T>> settingsList;
settingsList.Add(new Setting<int>());
settingsList.Add(new Setting<string>()); 

I've tried IList<Setting<T>> but this seems not possible since the compiler doesn't find Type T.

I know that I could use object but I want it to be strongly typed. So my question is if there is a possibility of getting this working.

like image 649
Tokk Avatar asked Jun 05 '11 10:06

Tokk


People also ask

Can you add a list to a list C#?

CSharp Online TrainingUse the AddRange() method to append a second list to an existing list. list1. AddRange(list2);


1 Answers

Generic types do not have a common type or interface amongst concrete definitions by default.

Have your Setting<T> class implement an interface (or derive from a common class) and create a list of that interface (or class).

public interface ISetting { }

public class Setting<T> : ISetting
{
    // ...
}

// example usage:
IList<ISetting> list = new List<ISetting>
{
    new Setting<int> { name = "foo", value = 2 },
    new Setting<string> { name = "bar", value "baz" },
};
like image 194
Jeff Mercado Avatar answered Oct 14 '22 12:10

Jeff Mercado