Awkward title I know, this is best explained in code. Given a set of classes:
public abstract class MyBaseType
{
public string Message { get; set; }
}
public class MySuperType : MyBaseType
{
public string AdditionalInfo { get; set; }
}
public class MyOtherSuperType : MyBaseType
{
public DateTime Started { get; set; }
public DateTime Finished { get; set; }
}
Is there a way to write a generic method that calls a non-generic method passing the generic type whilst interpreting the passed type as its actual type and not the base type. That is, I want to write something like this:
public void OutputFormattedTypeInfo<T>(T theType) where T : MyBaseType
{
OutputFormattedTypeInfo(theType as T);
}
public void OutputFormattedTypeInfo(MySuperType theType)
{
System.Console.WriteLine(String.Format("{0} and {1}", theType.Message, theType.AdditionalInfo));
}
public void OutputFormattedTypeInfo(MyOtherSuperType theType)
{
System.Console.WriteLine(String.Format("{0} - Start: {1}, End: {2}", theType.Message, theType.Started, theType.Finished));
}
But obviously theType as T is interpreted as the base type. I know I can use reflection like this:
Type type = typeof(MyBaseTypeDisplayFormatter);
MethodInfo method = type.GetMethod(
"FormatSpecific",
BindingFlags.Instance | BindingFlags.NonPublic,
null,
new[] { update.GetType() },
null);
return (MyBaseTypeDataItem)method.Invoke(this, new object[] { update });
but it just feels inelegant. Is there a better way?