Kieran
Kieran

Reputation: 306

How do I create a List<Item<T>>

Just trying to get my head around this one. Consider the following code.

public class Setting<T> where T: struct
{
    public string  Name { get; set; }
    public T Value { get; set; }
}

public class SettingsDto
{
    public List<Setting<>> Settings{ get; set; }
}

The issue is in the SettingsDto class. My Settings property wants me to specify a type for List>. All I know right now is that T must be a struct. How can I create a list of Settings such that I can add to it later - perhaps at runtime. Is there a way around this ?

Many thanks for all replies.

Upvotes: 0

Views: 178

Answers (4)

Dieter Meemken
Dieter Meemken

Reputation: 1967

Does it has to be struct? Otherwise You could use

public List<Setting<object>> Settings { get; set; }

and cast it when needed.

If it is not for performance reasons, you could put the struct inside a class.

Upvotes: 0

John Alexiou
John Alexiou

Reputation: 29274

You can only do it if all settings have something in common. Consider using an interface like this:

public interface ISetting
{
    string Name { get; set; }
}
public class Setting<T> : ISetting
    where T : struct
{
    public string Name { get; set; }
    public T Value { get; set; }
}

public class SettingsDto
{
    public List<ISetting> Settings { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        var set=new SettingsDto();
        set.Settings=new List<ISetting>();
        set.Settings.Add(new Setting<int>() { Name="Setting1", Value=100 });
        set.Settings.Add(new Setting<double>() { Name="Setting2", Value=Math.PI });
        set.Settings.Add(new Setting<DateTime>() { Name="Setting3", Value=DateTime.Now });
        set.Settings.Add(new Setting<int>() { Name="Setting4", Value=200 });

        foreach(var setting in set.Settings.OfType<Setting<int>>())
        {
            Console.WriteLine("{0}={1}", setting.Name, setting.Value);
        }
        // Setting1=100
        // Setting4=200
    }
}

Upvotes: 1

Igor Quirino
Igor Quirino

Reputation: 1195

You must to pass T generic type to SettingsDto.

Try this:

public class Setting<T> where T: struct 
{
    public string Name { get; set; }
    public T Value { get; set; }
}

public class SettingsDto<T> where T: struct
{
    public List<Setting<T>> Settings { get; set; }
}

Upvotes: 2

Allon Guralnek
Allon Guralnek

Reputation: 16131

You can carry over the generic parameter over to SettingsDto:

public class SettingsDto<T> where T : struct
{
    public List<Setting<T>> Settings { get; set; }
}

Upvotes: 3

Related Questions