tags:

views:

1501

answers:

3

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.

+5  A: 

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

John Sheehan
+3  A: 

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.

Jon Skeet
Actually dynamic isn't *really* the type. It more just says, don't determine the actual type until runtime. You can use "is" on dynamic types and figure out what they really are.
John Sheehan
But dynamic is the type of the *variable* still, in the same way that if you declare "object x = new MemoryStream()" then the type of the variable is "object" whereas the type of the object the variable's value refers to is "MemoryStream".
Jon Skeet
I am trying to find the place where I read in MS lit that explained what I was trying to explain. I can't find it again. I've read too much info from PDC in the past two days.
John Sheehan
Actually, "dynamic" is the type of the variable. The object's underlying type is some (static) CLR type. It's only the method dispatch that's dynamic.
Curt Hagenlocher
If `dynamic` is the type of the variable then this should compile, right? dynamic x = GetDynamic(); var y = x; // y is also dynamic
dalle
@dalle: Yes, I believe that should be fine. I haven't tried it though.
Jon Skeet
+1  A: 

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

Mohsen Afshin