Click here to Skip to main content
12,503,838 members (32,758 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

4.9K views
Posted

Alternative to Activator.CreateInstance

, 31 Jan 2012 CPOL
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)

Share

About the Author

jonathanjandrell
Web Developer
South Africa South Africa
C# Developer

You may also be interested in...

Pro
Pro

Comments and Discussions

 
GeneralReason for my vote of 1 Reason for my vote of one: if you kn... Pin
OriginalGriff31-Jan-12 8:30
mvpOriginalGriff31-Jan-12 8:30 
GeneralReason for my vote of 1 Unfortunately the problem with this ... Pin
Dean Oliver31-Jan-12 5:52
memberDean Oliver31-Jan-12 5:52 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.160919.1 | Last Updated 1 Feb 2012
Article Copyright 2012 by jonathanjandrell
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid