Activator

Activator allows you to create instance of an object when class name is unknown in compile time. It can be useful while creating plugins, reading data from external sources (like XML), etc.

See the example below. I have a ‘Person’ class in ‘Common’ library. Person class has got public parameterless constructor.
I can instantiate object of this class from another library (i.e. unit test) passing name of the dll and class (with namespace) in strings to Activator.
Notice: You must reference Microsoft.CSharp library to use ‘dynamic’ keyword.

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Windows;

namespace AnyTest
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Windows;

namespace AnyTest
{
    [TestClass]
    public class ActivatorTests
    {
        [TestMethod]
        public void TestMethod1()
        {
            dynamic myPerson = Activator.CreateInstance("Common", "Common.Person").Unwrap();
            Assert.IsTrue(myPerson.Age == 0);
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s