How to instantiate a generic type object in C#?

The closest to determining and creating the generic type at runtime that you'll probably get (using a string that represents the type name) is instantiating it like this public class ClassB { public ClassB(string typeInfo) { var typeOfT = Type. GetType(typeInfo); var type = typeof(ClassA). MakeGenericType(typeOfT); var instance = Activator.

CreateInstance(type); } } Exposing that directly through a public field will not be doable unless you mark your field as dynamic, because otherwise it will need that generic type information up front public dynamic objA Also, the string that represents the type must be qualified enough so that it can be located without ambiguity by Type.GetType() For example SomeNamespace. ClassC instead of ClassC.

The closest to determining and creating the generic type at runtime that you'll probably get (using a string that represents the type name) is instantiating it like this. Public class ClassB { public ClassB(string typeInfo) { var typeOfT = Type. GetType(typeInfo); var type = typeof(ClassA).

MakeGenericType(typeOfT); var instance = Activator. CreateInstance(type); } } Exposing that directly through a public field will not be doable unless you mark your field as dynamic, because otherwise it will need that generic type information up front. Public dynamic objA; Also, the string that represents the type must be qualified enough so that it can be located without ambiguity by Type.GetType().

For example, SomeNamespace. ClassC instead of ClassC.

Nice code. Although this can't solve the class definition problem, creating a generic type is a neat trick. – Paul Keister Sep 30 at 5:32.

Use object o = Activator. CreateInstance(constructed); this came from MSDN msdn.microsoft.com/en-us/library/system.... edit we use it in extension methods like; public static object DefaultValue(this Type targetType) { return targetType. IsValueType?Activator.

CreateInstance(targetType) : null; } It's not a huge stretch to make it work with generics.

– BoltClock Sep 30 at 4:59 You will fall into my soultion because of use object type – Artur Mustafin Sep 30 at 5:22.

Since objA is part of the definition of ClassB, ClassB will have to have to have a type parameter if ClassA has a type parameter, i.e. Public ClassB { public ClassA objA ... } If the type of objA is not known at compile time it will have to be of type Object or a non-generic base or interface. There's no middle ground.

The goal is to use the 'TypeInfo' as a source of type information. – baboonWorksFine Sep 30 at 5:11 @baboonWorksFine - of course it's possible to construct type definitions dynamically - that's how the C# compiler works! But you are tying to go beyond the limits of C# class definition syntax – Paul Keister Sep 30 at 5:25.

There is no reason to use generics for the types not known at compile time, because generics is used only for the KNOWN types, which means you can always make a substitution of a generic parameter with a type. The only matching type in the questioned situation is object type which is a base class for the all object types, and is always known to the compiler. Public ClassB{ public ClassA objA; public ClassB(string TypeInfo){ objA = new ClassA(); } ... } About your question... The only way to use a type not known at compile time is resolve the type at run time, make the ClassB generic, and use ILGenerator() for the generic class A to instantiate of construction of that class at the run-time.

Public ClassB{ public ClassA objA; public ClassB(){ objA = new ClassA(); } ... }.

– Tim Sep 30 at 4:49 The question itself is incorrect. There is no reason to use generics for types, being resloved at runtime – Artur Mustafin Sep 30 at 5:18 @Tim: Wouldn't using a generics to the types, not known at compile time to defeat of use optimizing compiler? – Artur Mustafin Sep 30 at 5:25 Removed my downvote now that you actually explained your answer.

Others will not always understand your point if you only provide code. – Kublai Khan Sep 30 at 5:29 @Artur - Well, yes. The question itself didn't make much sense to me, but I figured maybe there was some nuance the OP was aware of (or constrained by) that I didn't know about.

– Tim Sep 30 at 5:37.

Generics are like Templates in C++. If you write ClassA and ClassA two classes will be generated by the Compiler (one for string and one for int) and linked with the used Code. So it isn't possible to define the Type of a generic at runtime.

I think what your are looking for is the "RealProxy"/"TransparentProxy", where every Call to Method or Property will be redirected to one Invoke Method. Public class MyProxy:RealProxy{ public MyProxy(Type t):base(t){ } public override IMessage Invoke(IMessage myIMessage){ //every MethodCall or Propertycall will go here. } } public class OtherClass{ void DoSome(){ MyProxy proxy = new MyProxy(typeof(IMyInterface)); IMyInterface ifc = (IMyInterface)proxy.

GetTransparentProxy(); ifc.CallAMethod(); } } RealProxy Reference http://msdn.microsoft.com/en-us/library/system.runtime.remoting.proxies.realproxy.aspx.

Templates are nothing like generics. Generics are resolve at run time while templates are resolved at compile time. – Dani Sep 30 at 5:32 As Far as I know is this true, but in my example the ValueType generic and the ReferenceType Generic can't be reused and 2 Templates are created by the compiler.

The concept behind templates and generics is the same the implementation in C#/. NET is different indeed. – oberfreak Sep 30 at 8:45 C# never generates different template for different types, it will always be just one code, unlike C++ – Dani Sep 30 at 14:52 My mistake, I meant the JIT-compiler which is doing this.As far as I understood: The code generated by the JIT is reused for reference types for value types it has to be converted to x86 or x64 native code and so can't be reused for other value types.

So 2 "templates" exist in the memory one for string and one for int. I'm not sure if you can instruct the JIT to do this for you explicit and link it (typesafe) with your code. – oberfreak Sep 30 at 15:36.

The closest to determining and creating the generic type at runtime that you'll probably get (using a string that represents the type name) is instantiating it like this. Exposing that directly through a public field will not be doable unless you mark your field as dynamic, because otherwise it will need that generic type information up front. Also, the string that represents the type must be qualified enough so that it can be located without ambiguity by Type.GetType().

For example, SomeNamespace. ClassC instead of ClassC.

Writing a good decorator is no different then writing a good function. Which means, ideally, using docstrings and making sure the decorator is included in your testing framework You should definitely use either the decorator library or, better, the functools.wraps() decorator in the standard library (since 2.5) Beyond that, it's best to keep your decorators narrowly focused and well designed. Don't use args or kw if your decorator expects specific arguments.

And do fill in what arguments you expect, so instead of: def keep_none(func): def _exec(*args, **kw): return None if args0 is None else func(*args, **kw) return _exec use def keep_none(func): """Wraps a function which expects a value as the first argument, and ensures the function won't get called with *None*. If it is, this will return *None*. >>> def f(x): ... return x + 5 >>> f(1) 6 >>> f(None) is None Traceback (most recent call last): ... TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' >>> f = keep_none(f) >>> f(1) 6 >>> f(None) is None True""" @wraps(func) def _exec(value, *args, **kw): return None if value is None else func(value, *args, **kw) return _exec.

Writing a good decorator is no different then writing a good function. Which means, ideally, using docstrings and making sure the decorator is included in your testing framework. You should definitely use either the decorator library or, better, the functools.wraps() decorator in the standard library (since 2.5).

Beyond that, it's best to keep your decorators narrowly focused and well designed. Don't use *args or **kw if your decorator expects specific arguments. And do fill in what arguments you expect, so instead of: def keep_none(func): def _exec(*args, **kw): return None if args0 is None else func(*args, **kw) return _exec ... use ... def keep_none(func): """Wraps a function which expects a value as the first argument, and ensures the function won't get called with *None*.

If it is, this will return *None*. >>> def f(x): ... return x + 5 >>> f(1) 6 >>> f(None) is None Traceback (most recent call last): ... TypeError: unsupported operand type(s) for +: 'NoneType' and 'int' >>> f = keep_none(f) >>> f(1) 6 >>> f(None) is None True""" @wraps(func) def _exec(value, *args, **kw): return None if value is None else func(value, *args, **kw) return _exec.

Use functools to preserve the name and doc. The signature won't be preserved. Directly from the doc.

>>> from functools import wraps >>> def my_decorator(f): ... @wraps(f) ... def wrapper(*args, **kwds): ... print 'Calling decorated function' ... return f(*args, **kwds) ... return wrapper ... >>> @my_decorator ... def example(): ... """Docstring""" ... print 'Called example function' ... >>> example() Calling decorated function Called example function >>> example. __name__ 'example' >>> example. __doc__ 'Docstring.

Its good ettiquete to make wiki answers to your own questions. – voyager Sep 11 '09 at 14:42 that does make sense – Casebash Sep 11 '09 at 23:34.

Beyond that, it's best to keep your decorators narrowly focused and well designed. Don't use *args or **kw if your decorator expects specific arguments.

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions