How does reflection handle this? I decided to go test it.
I started by testing how it handles the dynamic nature of the variable, like this:
dynamic dyn = "string"; Console.WriteLine(dyn.GetType()); dyn = 1; Console.WriteLine(dyn.GetType()); dyn = 1L; Console.WriteLine(dyn.GetType());And happily it turns out we get the correct type after each assignment, the output will look like this:
System.String System.Int32 System.Int64The next thing I tested were how dynamic method parameters were handled. I created a method like this:
public void Test(dynamic dyn) { }What type would reflection return for the dyn parameter?
The following code gets type parameter type of the method, and prints it to the console:
MethodInfo mi = typeof(Program).GetMethod("Test"); ParameterInfo[] pi = mi.GetParameters(); foreach (ParameterInfo info in pi) Console.WriteLine(info.ParameterType);The output will be:
System.ObjectWhich also are the only possible assumption which can be made about the parameter, as it can be any type deriving from Object.
So how do you see, using reflection, if a variable are declared dynamic? Well at the time of this writing, it does not look like it is possible. This is suspicion are further strengthened by the following paragraph taken from the MSDN article linked in the beginning of the post:
Type dynamic behaves like type object in most circumstances. However, operations that contain expressions of type dynamic are not resolved or type checked by the compiler. The compiler packages together information about the operation, and that information is later used to evaluate the operation at run time. As part of the process, variables of type dynamic are compiled into variables of type object. Therefore, type dynamic exists only at compile time, not at run time.As all variables of type dynamic are compiled into object types, then reflection returns the correct result by returning Object, when the variable hasn't be assigned another value.