Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Alternative to Activator.CreateInstance

0.00/5 (No votes)
31 Jan 2012 1  
I've tried a few different ways to dynamically create an object of 'unknown' type.This is my final, simple result: public static T Create() { Type type = typeof(T); return (T)type.Assembly.CreateInstance(type.FullName); ...
I've tried a few different ways to dynamically create an object of 'unknown' type.

This is my final, simple result:


C#
        public static T Create<T>()
        {
            Type type = typeof(T);
            return (T)type.Assembly.CreateInstance(type.FullName);
        }
</t>



Ok, I'm getting a little flak here.
This is just a simple example.

In my project I deal with a lot of data objects, not all know at compile time, as some classes / objects may be from other separate (dynamically loaded) assemblies, yet still within the AppDomain.
A similar implementation of the code above allows my worker class to dynamically create any data object, and populate it.
As far as code-costs go, this is a very light simple method. I'm still yet to check CPU-costs.
If anybody has reliable stats on CPU costs please let me know.

C#
private static T From<T>(IDataReader reader, Type type)
{
    dynamic obj = type.Assembly.CreateInstance(type.FullName);
    ...
    return obj;
}


This code did / does not work for me as the compiler moans about the "new" keyword for the template "T".
C#
object obj = new T();

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here