Click here to Skip to main content
15,888,176 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I'm unable to call the Create<> function due to compile errors.
Any ideas?
enum ReportTypes
{
    Report1,
    Report2,
    Report3 
}

abstract class Report
{
    protected abstract bool Run();
}

class Report1 : Report
{
    protected override bool Run()
    { return true; }
}

class Report2 : Report
{
    protected override bool Run()
    { return true; }
}

class Report3 : Report
{
    protected override bool Run()
    { return true; }
}
class ReportFactory
{
    private static Dictionary<ReportTypes, Type> Reports = new Dictionary<ReportTypes, Type>()
    {
      {ReportTypes.Report1, typeof(Report1) },
      {ReportTypes.Report2, typeof(Report2)},
      {ReportTypes.Report3, typeof(Report3)},
    };

    static Report Create<T>() where T : Report, new()
    {
        return new T();
    }

    public static Report GetReport(ReportTypes reportType)
    {
        //Unable to get this line to work
        return ReportFactory.Create<Reports[reportType]>();
    }

}


What I have tried:

return ReportFactory.Create<typeof(Reports[reportType])>();
and
return ReportFactory.Create<Reports[reportType].GetType()>();

I know I can simply do this but, wanted to use the static Create function instead.
Report = (Report)ClassFactory.Create(Reports[reportType].GetType());
Posted
Updated 2-Jan-18 4:30am

You can do this using reflection

public static Report GetReport(ReportTypes reportType)
{
    Type t = Reports[reportType];

    MethodInfo method = typeof(ReportFactory)
        .GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
        .First(m => m.Name == "Create");

    MethodInfo genericMethod = method.MakeGenericMethod(t);
    return (Report)genericMethod.Invoke(null, null);
            
}
 
Share this answer
 
Comments
Thomas Daniels 2-Jan-18 12:54pm    
+5
They way you're using generics, isn't supported in C#. Between < and >, the name of a type is expected, not a Type object that isn't known at compile-time.

To create something based on a Type object, you can use Activator.CreateInstance[^].
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900