Search code examples
c#system.reflectiontypeofgettype

Reflection doesn't get the custom class in C#


I created a method to return a default field value from any class. I am trying to use Reflection to get the value, but it doesn't work.

Here is the class with the default value that I want (StoredProcedure):

namespace Services.Data.Report
{
  public class PayrollReport
  {
    public string FullName { get; set; }
    public DateTime WeekStart { get; set; }
    public decimal PerDiem { get; set; }
    public decimal StPay { get; set; }
    public decimal OtPay { get; set; }
    public decimal StraightHours { get; set; }
    public decimal OverTimeHours { get; set; }

    [DefaultValue("report_payrollSummary")]
    public string StoredProcedure { get; set; }
  }
}

I have this method that will allow me to pass the name of the class, and hopefully get the desired field value:

namespace Services
{
  public class DynamicReportService : IDynamicReportService
  {     
    public string GetDynamicReport(string className)
    {
        System.Reflection.Assembly assem = typeof(DynamicReportService).Assembly;
        var t = assem.GetType(className);
        var storedProcedure = t?.GetField("StoredProcedure").ToString();
        return storedProcedure;
    }
  }
}

I have also tried this, but get the same results:

var t = Type.GetType(className);

The problem is that t is never set.

I am trying to call it with something like this:

var storedProc = _dynamicReportService.GetDynamicReport("Services.Data.Report.PayrollReport");

Is there another way to pass the Class by name and be able to access the fields, methods, and other properties?


Solution

  • Try this:

    System.Reflection.Assembly assembly = typeof(DynamicReportService).Assembly;
    var type = assembly.GetType(className);
    var storedProcedurePropertyInfo = type.GetProperty("StoredProcedure"); 
    var defaultValueAttribute = storedProcedurePropertyInfo.GetCustomAttribute<DefaultValueA‌​ttribute>();
    return defaultValueAttribute.Value.ToString();
    

    First we will get the StoredProcedure PropertyInfo from the type, then we will look for the property DeafultValueAttribute using GetCustomAttribute<T> extension and in the end we will take the attribute value and return it.