Reputation: 25
I want to return Table List with there class object and this call also generic, I don't want to use any Non-Strong type List like ArrayList on any other.
public List<T> GetTables()
{
var tbls = new List<T>();
tbls.Add(new Table<Table1>() { Name = "Table1"});
tbls.Add(new Table<Table2>() { Name = "Table2"});
tbls.Add(new Table<Table3>() { Name = "Table3"});
return tbls;
}
in above Method, Table1, Table2, and any type table class object... There classes has no any based class, These classes use to Set of table properties with custom format.
I want to return it.
Please help me if anyone have any idea.
thank you.
Upvotes: 0
Views: 2530
Reputation: 409
If the only common thing of the list's components is that they are Table<>
generic objects, if there isn't any interface or common base class between Table1
/Table2
/Table2
, you can simply treat them as object
:
public List<Table<IGenerateData>> GetTables()
{
var tbls = new List<Table<IGenerateData>>();
tbls.Add(new Table<Table1>() { Name = "Table1"});
tbls.Add(new Table<Table2>() { Name = "Table2"});
tbls.Add(new Table<Table3>() { Name = "Table3"});
return tbls;
}
public interface IGenerateData
{
void GenerateData();
}
public class Table1 : IGenerateData
{
}
Upvotes: 2
Reputation: 36
You can't use generic type with the List without specifying type parameter explicitly. Alternatively, you can create a base class or interface that would be a parameter for the List.
I mean:
public static List<ITable> GetTables()
{
var tbls = new List<ITable>();
tbls.Add(new Table<Table1> { Name = "Table1"});
tbls.Add(new Table<Table2> { Name = "Table2"});
tbls.Add(new Table<Table3> { Name = "Table3"});
return tbls;
}
public class Table<T> : ITable
{
public T TableInstance { get; set; }
public Type TableType => typeof(T);
public string Name { get; set; }
}
public interface ITable
{
Type TableType { get; }
public string Name { get; set; }
}
Upvotes: 1