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.
Use this overload of the CreateInstance method:
See: http://msdn.microsoft.com/en-us/library/wcxyzt4d.aspx
Good answers but unusable on the dot net compact framework. Here is a solution that will work on CF.Net...
When I benchmarked performance of
(T)FormatterServices.GetUninitializedObject(typeof(T))
it was slower. At the same time compiled expressions would give you great speed improvements though they work only for types with default constructor. I took a hybrid approach:This means the create expression is effectively cached and incurs penalty only the first time the type is loaded. Will handle value types too in an efficient manner.
Call it:
Note that
(T)FormatterServices.GetUninitializedObject(t)
will fail for string. Hence special handling for string is in place to return empty string.I originally posted this answer here, but here is a reprint since this isn't the exact same question but has the same answer:
FormatterServices.GetUninitializedObject()
will create an instance without calling a constructor. I found this class by using Reflector and digging through some of the core .Net serialization classes.I tested it using the sample code below and it looks like it works great: