0

I have an app that contains a lot of pages that need to be added to a report. The number of pages grows quickly so I want to be able to populate the report with them dynamically. The methods below return the list of pages correctly but I cant get it to add the page to the report.

I get Argument 1: cannot convert from 'System.Type' to 'Reports.Pages.PageBase' How can I correct this?

private void AddAllPages()
        {
            var pages = FindSubClassesOf<PageBase>();

            foreach (var pg in pages)
            {
              Report.Pages.Add(pg);
            }
        }

        public IEnumerable<Type> FindSubClassesOf<TBaseType>()
        {
            var baseType = typeof(TBaseType);
            var assembly = baseType.Assembly;

            return assembly.GetTypes().Where(t => t.IsSubclassOf(baseType));
        }
  • 2
    Confusing types and objects is rather a problem, the kind that requires a book, not an SO answer. There's no concrete advise to give here, creating an object of the types you found isn't going to give you a nicely ordered report at all. You'll have to think this through. – Hans Passant Sep 17 '14 at 21:56
  • The report object knows how to handle the pages it is given. So the order of the pages is not important. Just adding the pages to the report is the goal here. – Robert Meier Sep 17 '14 at 22:58

2 Answers2

0

You want to create an instance of each type:

Activator.CreateInstance(type)

If the types do not have default constructors, you will need to pass constructor arguments too.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • so using this example it would be private void AddAllPages() { var pages = FindSubClassesOf(); foreach (var pg in pages) { var newpage = Activator.CreateInstance(pg); Report.Pages.Add(newpage); } } is this correct? – Robert Meier Sep 17 '14 at 23:36
  • @RobertMeier: Yes, except that `pg` is a misleading name. It's actually a type. – SLaks Sep 18 '14 at 00:08
  • Excelent. I will give this a try in the morning. Thank you! – Robert Meier Sep 18 '14 at 00:13
0

Discovering derived types using reflection

public static List<Type> FindAllDerivedTypes<T>()
{
    return FindAllDerivedTypes<T>(Assembly.GetAssembly(typeof(T)));
}

public static List<Type> FindAllDerivedTypes<T>(Assembly assembly)
{
    var derivedType = typeof(T);
    return assembly
        .GetTypes()
        .Where(t =>
            t != derivedType &&
            derivedType.IsAssignableFrom(t)
            ).ToList();

} 
Community
  • 1
  • 1
Chuck Buford
  • 321
  • 1
  • 9