I've seen many examples of this tool which abstracts away the cumbersome syntax of Reflection. However none demonstrate instantiation of an unknown type. Is it safe to assume this isn't possible with "dynamic"?
- which tool are you talking about?Petar Ivanov– Petar Ivanov2011-07-24 01:16:19 +00:00Commented Jul 24, 2011 at 1:16
- and how does it "abstract away the syntax of Reflection"?Petar Ivanov– Petar Ivanov2011-07-24 01:19:14 +00:00Commented Jul 24, 2011 at 1:19
- 1One is able to assume the existence of properties and methods rather than use Reflection as the middle man.S. Valmont– S. Valmont2011-07-24 01:26:39 +00:00Commented Jul 24, 2011 at 1:26
3 Answers
Logically, it's impossible to instantiate an unknown type -- to instantiate a type, something must know what it is.
dynamic is useful for manipulating values of an unknown type (by assuming that it is capable of certain operations, which will fail at runtime if they are in fact not possible). To instantiate any type, however, you either need to use compile-time instantiation (e.g. using a C# constructor call), or else you need an instance of Type that corresponds to your desired type.
3 Comments
Construct method to either be (1) parameterized by the desired type (meaning that the type must be known at compile time) or (2) take a Type object as a parameter, meaning that the type must be known at runtime, or (3) take a string which gets passed to Type.GetType (after which it's the same as #2). That's what I meant by "something must know what it is".Construct(string typeName, params Object[] args) as the signature. I can't speak for the OP, but I assumed he/she did know what type they wanted to instantiate, just like you would need to know the name of the method you want to call when you call a method dynamically.The compiler can use the dynamic keyword so that the dlr will construct a type, but it's designed to late bind the arguments of a constructor rather than the type to be constructed. The opensource framework ImpromptuInterface abstracts the dlr calls, including the constructor. If you need to call a constructor that has arguments this will run about 5 times faster than using reflection/Activator.
var x = Impromptu.InvokeConstructor(Type.GetType("SomeType"),args...); Comments
I don't know what your goal is... but do you mean something like
dynamic X = Type.GetType("SomeUnknownType").GetConstructor(null).Invoke(null); ?
the above just calls the default (parameterless) constructor of the Type "SomeUnknownType" and assign the resulting instance to a dynamic .