Reputation: 137
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
Upvotes: 2
Views: 1151
Reputation: 54127
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();
Upvotes: 9
Reputation: 1064004
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).
Upvotes: 2