Search code examples
c#genericsreturngeneric-listgeneric-collections

How to return Generic List with Generic Class Object in c#?


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.


Solution

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