2

I have the list which i would like to map to List. However, there is no compiler error, but at runtime result is coming as null. Getting a generic List<T> will help me make my code generic and reuse for different objects.

private static List<T> GetIndexData(DataAdapter dataAdapter)
{
  Type type = typeof(T);
  List<T> result = new List<T>();

  if (typeof(Category).IsAssignableFrom(typeof(T)))
  {
    var output = ItemStoreDataManager.GetAllCategoryNames(dataAdapter);                
    result = output as List<T>;                    
  }
  return result;
}

Above code result is coming as null.

internal static List<Category> GetAllCategoryNames(DataAdapter dataAdapter)
{
  List<Category> result = new List<Category>();

  ...........
  return result;
}

Please help.

Thanks

1
  • If the types T and U are assigment compatible, it does not automatically mean that List<T> and List<U> are assignment compatible as well. Commented Dec 31, 2012 at 15:52

2 Answers 2

9

The error is in the following line of code:

result = output as List<T>;

C# won't let you cast a List<TSomething> to List<TSomethingElse> using the as operator. You're seeing a null value for the reasons specified in MSDN...

The as operator is like a cast operation. However, if the conversion is not possible, as returns null instead of raising an exception.

Note that the as operator only performs reference conversions and boxing conversions. The as operator cannot perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.

Your options are either to build up your new list item-by-item using a foreach loop, or use Enumerable.Cast (from System.Linq) which will do this for you:

output.Cast<T>().ToList();
Sign up to request clarification or add additional context in comments.

1 Comment

"Your options are either to build up your new list item-by-item using a foreach loop, or [...]" Keep in mind that's exactly what the LINQ method is doing, it's just hiding it from you.
2

If you are specializing by type, frankly generics might not be the best choice. I wonder if taking a Type instance, and returning non-generic IList would be more appropriate. However: if we use type equality, you can just cast it via object:

if (typeof(Category) == typeof(T))
{
    var output = ItemStoreDataManager.GetAllCategoryNames(dataAdapter);
    result = (List<T>)(object)output;
}

If you are fussy about the IsAssignableFrom, then it is much tougher; a List<SuperCategory> cannot be cast to a List<Category> (or the opposite). You can either create a new list (see Richard Ev's answer), or use IEnumerable<Category> (that does support variance).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.