Saturday, August 15, 2015

Create objects from default constructor

Do you think that title sound redundant? If so, which method were you thinking of? Because there are several! Let's talk about those...and be sure to scroll to the bottom for a performance comparison!

Sample Class

Here is the class that we will be instantiating in our tests.

internal class TestClass
{
    public Guid Guid { get; private set; }
 
    public TestClass()
    {
        Guid = Guid.NewGuid();
    }
}

The new Keyword

This is the obviously, easier, fastest, normal way of instantiating an object...obviously.

[Fact]
public void NewDuh()
{
    var testObject = new TestClass();
    Assert.NotNull(testObject.Guid);
}

Activator.CreateInstance

This is a very simple and common way to instantiate an object from a Type object. It has an overload that takes a params object collection to let you use other, non default, constructors.

[Fact]
public void ActivatorCreateInstance()
{
    var type = typeof (TestClass);
    var instance = Activator.CreateInstance(type);
            
    var testObject = Assert.IsType<TestClass>(instance);
    Assert.NotNull(testObject.Guid);
}

ConstructorInfo.Invoke

Get the constructor info from a type is the only none generic way to check if it has a default constructor.

[Fact]
public void TypeGetConstructor()
{
    var type = typeof(TestClass);
 
    var constructor = type.GetConstructor(Type.EmptyTypes);
    Assert.NotNull(constructor);
            
    var instance = constructor.Invoke(new object[0]);
 
    var testObject = Assert.IsType<TestClass>(instance);
    Assert.NotNull(testObject.Guid);
}

Generic new() Constraint

If you have the generic type constraint you can actually use the new() constraint to enforce that the type has a default constructor and invoke it directly.

[Fact]
public void NewConstraint()
{
    var testObject = Create<TestClass>();
    Assert.NotNull(testObject.Guid);
}
        
private static T Create<T>()
    where T : new()
{
    return new T();
}

Performance

So how do these compare with regard to performance? They are all very fast, but here is a break down of one million invokes each:

Method Milliseconds
The new Keyword 420
Activator.CreateInstance 608
ConstructorInfo.Invoke 872
Generic new() Constraint 672

Enjoy,
Tom

No comments:

Post a Comment

Real Time Web Analytics