Showing posts with label new. Show all posts
Showing posts with label new. Show all posts

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);
}
Real Time Web Analytics