Monday, January 25, 2010

Reflection on dynamic variables in .NET 4.0

One of the new things in .NET 4.0, are the ability to create dynamic variables, http://msdn.microsoft.com/en-us/library/dd264741(VS.100).aspx.
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.Int64
The 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.Object
Which 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.

No comments:

Post a Comment