How to cast a list of specific type to a list of generic type in c#

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.



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:


Need Your Help

How to speed up the page with lots of table cells?

php html css

In my project I have one table with 24*6*300 cells on one page (it's script for rendering the statistics) - 24 columns for hours * 6 columns for 10minutes * 300 rows. Every cell has tipsy popup with

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.