I have created a dynamic method to create an instance of different type, but not sure why it is giving above mentioned error at compile time, also do I have to again cast the return value to the specified type?
internal static T GetInstance<T>()
{
dynamic obj = Activator.CreateInstance(typeof(T));
return obj;
}
private Foo f = GetInstance<Foo>();
Why don’t you just use what MSDN recommends, which is the following:
http://msdn.microsoft.com/en-us/library/0hcyx2kd.aspx
EDIT:
Though, I don’t understand why you even want to have this method?
Instead of calling
var x = GetInstance<Foo>();, you could just dovar x = new Foo();since Foo must have parameterless constructor if you want to callGetInstance<T>()withFooas the type parameter ( or am I missing something? ).