Mike Taulty's Blog
Bits and Bytes from Microsoft UK
C# 4, Dynamic Overloads

Blogs

Mike Taulty's Blog

Elsewhere

Archives

Another experiment with C# 4 and the “dynamic type”. I was playing with this code below and wasn’t 100% sure what’d happen at the point where we hit the 2 lines that I’ve flagged with a * below.

That is – if I’m doing dynamic method resolution and I pass a “dynamic parameter” then are they treated as object or are they treated as their actual types with respect to resolution. You can see how it actually seems to work below;

class MyType
{
  public void Method(int x, int y)
  {
    Console.WriteLine("Int function");
  }
  public void Method(string s, string t)
  {
    Console.WriteLine("String function");
  }
  public void Method(object o, object p)
  {
    Console.WriteLine("Object function");
  }
}
class Program
{
  static void Main(string[] args)
  {
    dynamic d = new MyType();
    d.Method(10, 20); // Calls the int version.
    d.Method("abc", "def"); // Calls the string version.  
    d.Method((object)10, (object)20); // Calls the object version.
    d.Method((object)"abc", (object)"def"); // Calls the object version.

    // *
    d.Method((dynamic)10, (dynamic)20); // Calls the int version.
    d.Method((dynamic)"abc", (dynamic)"def"); // Calls the string version.

    // Repeat of the last 4 cases.
    d.Method(GetInt(), GetInt()); // Calls the object version.
    d.Method(GetString(), GetString()); // Calls the object version.
    d.Method(GetDynamicInt(), GetDynamicInt()); // Calls the int version.
    d.Method(GetDynamicString(), GetDynamicString()); // Calls the string version.
  }
  static object GetString()
  {
    return ("abc");
  }
  static object GetInt()
  {
    return (5);
  }
  static dynamic GetDynamicInt()
  {
    return (5);
  }
  static string GetDynamicString()
  {
    return ("abc");
  }
}

Update - I got a ping that pointed at these articles which give a lot more detail and are really useful;

Dynamic in C#

Dynamic in C# II- Basics

Dynamic in C# III- A slight twist

Dynamic in C# IV- The Phantom Method

Dynamic in C# V- Indexers, Operators, and More!

Dynamic in C# VI- What dynamic does NOT do

Dynamic in C# VII- Phantom Method Semantics


Posted Fri, Mar 6 2009 2:16 AM by mtaulty

Comments

Dew Drop – March 6, 2009 | Alvin Ashcraft's Morning Dew wrote Dew Drop – March 6, 2009 | Alvin Ashcraft's Morning Dew
on Fri, Mar 6 2009 5:11 AM
Mike Taulty's Blog wrote C# 4, More scrappy thoughts on dynamic
on Fri, Mar 6 2009 8:42 AM

NB: This comes from experimentation rather than being some kind of C# guru so apply a pinch of salt to

Arjan`s World » LINKBLOG for March 6, 2009 wrote Arjan`s World » LINKBLOG for March 6, 2009
on Fri, Mar 6 2009 12:58 PM
DotNetShoutout wrote C# 4, Dynamic Overloads - Mike Taulty's Blog
on Fri, Mar 6 2009 2:14 PM

Thank you for submitting this cool story - Trackback from DotNetShoutout