O'Reilly logo

Programming C# 4.0 by Jesse Liberty, Matthew Adams, Ian Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The dynamic Type

C# 4.0 introduces a new type called dynamic. In some ways it looks just like any other type such as int, string, or FileStream: you can use it in variable declarations, or function arguments and return types, as Example 18-4 shows. (The method reads a little oddly—it’s a static method in the sense that it does not relate to any particular object instance. But it’s dynamic in the sense that it uses the dynamic type for its parameters and return value.)

Example 18-4. Using dynamic

static dynamic AddAnything(dynamic a, dynamic b)
{
    dynamic result = a + b;
    Console.WriteLine(result);
    return result;
}

While you can use dynamic almost anywhere you could use any other type name, it has some slightly unusual characteristics, because when you use dynamic, you are really saying “I have no idea what sort of thing this is.” That means there are some situations where you can’t use it—you can’t derive a class from dynamic, for example, and typeof(dynamic) will not compile. But aside from the places where it would be meaningless, you can use it as you’d use any other type.

To see the dynamic behavior in action, we can try passing in a few different things to the AddAnything method from Example 18-4, as Example 18-5 shows.

Example 18-5. Passing different types

Console.WriteLine(AddAnything("Hello", "world").GetType().Name); Console.WriteLine(AddAnything(31, 11).GetType().Name); Console.WriteLine(AddAnything("31", 11).GetType().Name); Console.WriteLine(AddAnything(31, 11.5).GetType().Name); ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required