Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List<T> with different values types

Tags:

c#

C#. I have a class:

public class SQLValue<T> 
{ 
    public string nam { get; set; } 
    public string typ { get; set; } 
    public T val      { get; set; } 
}

now I want to create

List<SQLValue> lst = List<SQLValue>();

and add elements to it like that:

lst.Add(new List<SQLValue>(nam = "PlayerName", typ = "string", val = "Bot1"));
lst.Add(new List<SQLValue>(nam = "Ally", typ = "bool", val = true));
lst.Add(new List<SQLValue>(nam = "Levl", typ = "int",  val = 2));

so I want to have a list of class that contain the value val with different types. Is it real?

like image 950
user2698308 Avatar asked May 24 '18 05:05

user2698308


1 Answers

You can't.

Some base type is required. Obviously, you can always use List<object>, if you just want to store SQLValue<T> instances.

But, assuming, that you want to process list items depending on nam and typ properties, all you can do here is to extract some base class/interface:

public interface ISQLValue
{
    public string nam { get; set; } 
    public string typ { get; set; } 
    public object val { get; set; }
}

implement it in SQLValue<T> this way:

public class SQLValue<T> : ISQLValue
{ 
    public string nam { get; set; } 
    public string typ { get; set; } 

    public T val { get; set; } 

    object ISQLValue.val 
    {  
        get { return this.val; }
        set { this.val = (T)value; }
    }
}

and use List<ISQLValue> to store instances and process them:

var sqlValues = new List<ISQLValue>
{
    new SQLValue<string> { nam="PlayerName", typ="string", val="Bot1" }
    new SQLValue<bool> { nam="Ally", typ="bool", val=true }
    new SQLValue<int> { nam="Levl", typ="int", val=2 }
};

foreach (var value in sqlValues)
{
    Console.WriteLine($"nam = {value.name}, typ = {value.typ}, val = {value.val}");
}

That is, in case of some batch processing, ISQLValue will be used. But if you know T of particular ISQLValue, you can cast it to SQLValue<T> and use T val instead of object val.

like image 121
Dennis Avatar answered Nov 01 '22 03:11

Dennis