Click here to Skip to main content
15,880,469 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Alternative to Activator.CreateInstance

Rate me:
Please Sign up or sign in to vote.
1.00/5 (2 votes)
31 Jan 2012CPOL 9.3K   2
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
South Africa South Africa
C# Developer

Comments and Discussions

 
GeneralReason for my vote of 1 Reason for my vote of one: if you kn... Pin
OriginalGriff31-Jan-12 8:30
mveOriginalGriff31-Jan-12 8:30 
GeneralReason for my vote of 1 Unfortunately the problem with this ... Pin
Dean Oliver31-Jan-12 5:52
Dean Oliver31-Jan-12 5:52 
Reason for my vote of 1
Unfortunately the problem with this is it's not a solution sure it works. but what if you only know the type at run-time then how you going to use your create Method. you basically using a fancy way to call new Example(); Not to mention the fact it is virtually the same as Activator.CreateInstance. not an alternative. Did you even try to test the performance differences between all the implementations?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.