0

I have a method which accepts Generic Type. I want to cast it to List. I tried it with the following example. I am a novice in Generics.Below is what I tried.

    class Program
    {
        static void Main(string[] args)
        {
            Employee emp = new Employee();
            emp.Name = "a";
            emp.Id = 1;
            List<Employee> empList = new List<Employee>();
            empList.Add(emp);
            get(emp);
            get(empList);
        }

        public static void get<T>(T targetObj)
        {
            if (targetObj.GetType().IsGenericType)
            {
                 Base baseDo = targetObj as Base;//Getting null
                 List<Base> baseList = targetObj as List<Base>;//Getting null
            }
            else
            {
                Base p = targetObj as Base;
            }
        }
    }
    public class Base
    {
        public long Id { get; set; }
    }
    public class Employee : Base
    {
        public string Name { get; set; }
    }
Midhun Mathew
  • 2,147
  • 8
  • 28
  • 45
  • `IsGenericType` is only `true` when `get()` is called with `empList`. And `empList` is of type `List`. This is a different (and not assignable) type than `Base` or `List` (classes are invariant, `List` is _not_ assignable to `List`). Thatswhy the `as` operators return `null`. – René Vogt Aug 05 '16 at 08:17
  • 2
    Well a `List` isn't a `List`, for reasons that are covered elsewhere. You could cast to `IEnumerable` though... – Jon Skeet Aug 05 '16 at 08:17
  • 2
    In C# `List` can't be casted to `List` Mode details here http://stackoverflow.com/questions/1169215/why-cant-listparent-listchild – Adnan Umer Aug 05 '16 at 08:20
  • Use Linq to Cast from one type to another like: var employeeList = targetObj as List; var baseList = **employeeList.Cast().ToList()**; – Nick Niebling Aug 05 '16 at 08:28

0 Answers0