Question

I'm trying to create an instance of a class that I can add to a list in a generic way..

I know the type of class that needs to be made and i've been able to make an object of the class using the code below but I have not found a way to create a cast that will allow me to add this to a list.. any ideas?

T is the same as objType

public static List<T> LoadList(string fileName, Type objType)
{
    List<T> objList = new List<T>();
    object o = Activator.CreateInstance(objType);
    objList.Add((**o.GetType()**)o);
    return objList;
}

if theres a better way of doing this too im open to ideas :)

Was it helpful?

Solution

Just use the non-generic API:

((IList)objList).Add(o);

I'm also assuming that type is a generic type-parameter; just to say: type is confusing for this; T or TSomethingSpecific would be more idiomatic.

Also: this line needs fixing:

List<type> objList = new List<type>(); // <=== not new List<Object>

OTHER TIPS

Given that <type> is the same as objType, I'd suggest dropping the reflection and using the where T : new() type constraint:

public static List<T> LoadList(string fileName) 
    where T : new()
{
    List<T> objList = new List<T>();
    objList.add(new T());
    return objList;
}

Edit:

If objType is a subclass of T, then I think something along these lines should work:

public static List<TListType, T> LoadList(string fileName)
    where T : TListType, new()
{
    List<TListType> objList = new List<TListType>();
    objList.add(new T());
    return objList;
}

You could user Zach Johnson's suggestion with the where constraint as it eliminates a duplicate specification of the type. However if the signature is set in stone, you could get by with a simple as cast, like:

public List<T> LoadList<T>(Type objType) where T : class
{
  List<T> objList = new List<T>();
  T item = (Activator.CreateInstance(objType) as T);
  objList.Add(item);
  return objList;
}

This also needs a where restriction, because in order to cast to a type, that type must be a reference type (aka class).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top