Skip to content

How to make List<T> work?

van tive

Asked Mar 24, 2007, 8:03 PM EDT2 answers
Share
LinkedInX

How to make generic List<T> for bool, Int16 , string  in the following code?

TypeScript
class myClass
{
string _dataType;
public List<Object> _list;
public myClass(string dataType)
 {
  _dataType=dataType;
 if (dataType=="bool")
    _list=new List<bool>();
 else if (dataType=="int16")
   _list=new List<Int16>();
 else if (dataType == "string")
   _list=new List<string>();
 else
   _list = new List<Object>();
 }
}

Error: Cannot implicitly convert type 'System.Collections.Generic.List<bool>' to 'System.Collections.Generic.List<object>'

2 Answers

Know the answer? Post it. Somebody with the same question will find it here.

  • Mike Gold
    0
    I don't think you can do this.  Templates are thought of as creating types at pre-compile time so the code here doesn't  really make sense.  what are you trying to do and perhaps we can suggest another means?

    best

    -Mike
    0
  • 0
    Consider applying the generic to your class if you want to encapsulate the generic list.
    Eg:
    public class myClass <T>
    {
        private List<T> _list = new List<T>();

    // Implement your code here using "T" as your type where needed rather than worrying about hard-coded types.
    }

    You can also restrict the types that your class supports.

    Eg: To restrict it to Int, Bool, or String
    public class myClass <T> where T : int, bool, string
    0