Can dynamic variables in C# 4.0 be members on a class or passed into or returned from methods? var from C# 3.0 couldn't but I haven't seen any mention anywhere of whether it is possible or not with dynamic.
All of the above. I tried them out in the VPC and was able to do all of these. See the 'New Features in C#' document here
Yes. There's a big difference between var
and dynamic
.
var
just means "let the compiler infer the real type of the variable".
dynamic
is the type of the variable - so anywhere you can specify a type, you can specify dynamic
instead, as I understand it. (I'm sure there are some exceptions to this, but that's the basic idea.)
EDIT: Chris Burrow's first blog entry on dynamic
(there's a second one already; expect more soon) gives an example class which uses dynamic
all over the place.
This code snippet from the book "CLR via C#, 3rd Ed" shows dynamic in action :
using System;
using System.Dynamic;
static class DyanmicDemo
{
public static void Main() {
for(Int32 demo =0; demo < 2; demo++) {
dynamic arg = (demo == 0) ? (dynamic) 5 : (dynamic) "A";
dynamic result = Plus(arg);
M(result);
}
}
private static dynamic Plus(dynamic arg) { return arg + arg; }
private static void M(Int32 n) { Console.WriteLine("M(Int32): " + n); }
private static void M(String s) { Console.WriteLine("M(String): " + s); }
}
When I execute Main, I get the following output:
M(Int32): 10
M(String): AA