65.9K
CodeProject is changing. Read more.
Home

Alternative to Activator.CreateInstance

starIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

1.00/5 (2 votes)

Jan 31, 2012

CPOL
viewsIcon

9770

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();