locked
Generic Method returning a generic list.... RRS feed

  • Question

  • User818699641 posted

    I am trying to a list of types that implement an interface. I have seen others ways you can do this with LINQ - but I want to do it something like the code below.. I am geting a compile time error on TypeList.Add(t); and I know why - as the compiler does not know the type of t and it might not match the generic T type of the method.

            public static List<T> GetListOfTypeFromRunningAssembly<T>()
            {
                List<T> TypeList = new List<T>();
                Assembly a = GetRunningAssembly();
                foreach (Type t in a.GetTypes())
                {
                    if (t is T)
                    {
                        TypeList.Add(t);
                    }
                }
                return TypeList;
            }



    The question is, how do I fix this using the approach I am already using?

    Thanks,

    Brad

    Wednesday, May 2, 2012 9:37 AM

Answers

  • User818699641 posted

    And two minutes later - get this to compile.. still need to make sure it works, but I think it will.

            public static List<T> GetListOfTypeFromRunningAssembly<T>()
            {
                List<object> TypeList = new List<object>();
                Assembly a = GetRunningAssembly();
                foreach (Type t in a.GetTypes())
                {
                    if (t is T)
                    {
                        TypeList.Add(t);
                    }
                }
                return TypeList as List<T>;
            }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 2, 2012 9:49 AM

All replies

  • User818699641 posted

    And two minutes later - get this to compile.. still need to make sure it works, but I think it will.

            public static List<T> GetListOfTypeFromRunningAssembly<T>()
            {
                List<object> TypeList = new List<object>();
                Assembly a = GetRunningAssembly();
                foreach (Type t in a.GetTypes())
                {
                    if (t is T)
                    {
                        TypeList.Add(t);
                    }
                }
                return TypeList as List<T>;
            }



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, May 2, 2012 9:49 AM
  • User-1910946339 posted

    Untested but I don't think it needs to be quite as complicated

    return Assembly.GetExecutingAssembly().GetTypes.OfType<T>();

    Wednesday, May 2, 2012 7:56 PM