6

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.

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

6 Comments

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.
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".
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.
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.
If dynamic is the type of the variable then this should compile, right? dynamic x = GetDynamic(); var y = x; // y is also dynamic
|
5

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

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.