Generic Method Executed with a runtime type [duplicate]-Collection of common programming errors

First we need to convert p.Value to the right type, since even if we know the type at compile time we can’t pass the string straight to the method…

DoSomething( "10" ); // Build error

For simple numeric types and DateTime, we can use

object convertedValue = Convert.ChangeType(p.Value, p.DisplayType);

Now we can use reflection to invoke the required generic method…

typeof(ClassExample)
    .GetMethod("DoSomething")
    .MakeGenericMethod(p.DisplayType)
    .Invoke(this, new object[] { p.Name, convertedValue });