Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Alternative to Activator.CreateInstance

, 31 Jan 2012
Rate this:
Please Sign up or sign in to vote.
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:
 

        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.
 
        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".
object obj = new T();

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

jonathanjandrell
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... PinmvpOriginalGriff31-Jan-12 8:30 
GeneralReason for my vote of 1 Unfortunately the problem with this ... PinmemberDean Oliver31-Jan-12 5:52 

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

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

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 1 Feb 2012
Article Copyright 2012 by jonathanjandrell
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid