If you have a generic type type, then Jeff Bridgman's answer is the best. If you only have a type object representing the type you want to build, you can use Activator.CreateInstance(Type) as suggested by Alex Lyman, but they told me that it is slow (I did not profile it personally, though).
However, if you build these objects very often, there is a more eloquent approach using dynamically compiled Linq expressions:
using System; using System.Linq.Expressions; public static class TypeHelper { public static Func<object> CreateDefaultConstructor(Type type) { NewExpression newExp = Expression.New(type);
Just call the delegate who was returned to you. You must cache this delegate because constantly recompiling Linq expressions can be expensive, but if you cache the delegate and reuse it every time, it can be very fast! I personally use a static search dictionary indexed by type. This function is useful when you are dealing with serialized objects where you can only know type information.
NOTE. This may fail if the type is not constructive or does not have a default constructor!
DaFlame Jul 09 '13 at 16:04 on 2013-07-09 16:04
source share