Take the following class as an example:
class Sometype
{
int someValue;
public Sometype(int someValue)
{
this.someValue = someValue;
}
}
I then want to create an instance of this type using reflection:
Type t = typeof(Sometype);
object o = Activator.CreateInstance(t);
Normally this will work, however because SomeType
has not defined a parameterless constructor, the call to Activator.CreateInstance
will throw an exception of type MissingMethodException
with the message "No parameterless constructor defined for this object." Is there an alternative way to still create an instance of this type? It'd be kinda sucky to add parameterless constructors to all my classes.
FormatterServices.GetUninitializedObject
not allow to create uninitialized string. You may get exception:System.ArgumentException: Uninitialized Strings cannot be created.
Please keep this in mind. – Extortioner