test

Page 186

}

}

Foo (x); Foo (y);

// 1 // 2

Runtime overload resolution is also called multiple dispatch and is useful in implementing design patterns such as visitor. If a dynamic receiver is not involved, the compiler can statically perform a basic check to see whether the dynamic call will succeed: it checks that a function with the right name and number of parameters exists. If no candidate is found, you get a compile-time error. If a function is called with a mixture of dynamic and static arguments, the final choice of method will reflect a mixture of dynamic and static binding decisions: static static static static

void void void void

X(object X(object X(string X(string

x, x, x, x,

static void Main() { object o = "hello"; dynamic d = "goodbye"; X (o, d); }

object string object string

y) y) y) y)

{Console.Write("oo");} {Console.Write("os");} {Console.Write("so");} {Console.Write("ss");}

// os

The call to X(o,d) is dynamically bound because one of its arguments, d, is dynamic. But since o is statically known, the binding—even though it occurs dynamically—will make use of that. In this case, overload resolution will pick the second implementation of X due to the static type of o and the runtime type of d. In other words, the compiler is “as static as it can possibly be.”

Uncallable Functions Some functions cannot be called dynamically. You cannot call: • Extension methods (via extension method syntax)

172 | C# 4.0 Pocket Reference


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.