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