prosseek
prosseek

Reputation: 190659

dynamic type casting in parameter in c#

I happen to see a code something like this.

function((dynamic) param1, param2);

When and why do we need this kind of dynamic type casting for parameters?

Upvotes: 5

Views: 420

Answers (1)

James Michael Hare
James Michael Hare

Reputation: 38397

It can be used to dynamically choose an overload of function(...) based on the type of param1 at runtime, for example:

public static void Something(string x)
{
    Console.WriteLine("Hello");
}

public static void Something(int x)
{
    Console.WriteLine("Goodbye");
}
public static void Main()
{
    object x = "A String";

    // This will choose string overload of Something() and output "Hello"
    Something((dynamic)x);

    x = 13;

    // This will choose int overload of Something() and output "Goodbye"
    Something((dynamic)x);
}

So even though x is a reference to object, it will decide at runtime what overload of Something() to call. Note that if there is no appropriate overload, an exception will be thrown:

    // ...
    x = 3.14;

    // No overload of Something(double) exists, so this throws at runtime.
    Something((dynamic)x);

Upvotes: 5

Related Questions