Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

method overloading and dynamic keyword in C#

I still haven't upgraded to 4.0 else I would have checked the code snippet myself. But I hope some expert can comment on this.

In following code, will the appropriate Print() method be called at runtime? Is it even legal in C# 2010 to call it that way?

public void Test()
{
    dynamic objX = InstantiateAsStringOrDouble();

    Print(objX);
}

public void Print(string s)
{
    Console.Write("string");
}

public void Print(double n)
{
    Console.Write("double");
}

Thanks!

like image 359
Vishal Seth Avatar asked Jan 27 '26 16:01

Vishal Seth


2 Answers

Yes, that does in fact work. It will check the usage of the dynamic at runtime and call the appropriate method, however you lose almost all of your compile-time checking, so I'd make sure that's really what you'd want to do.

like image 129
James Michael Hare Avatar answered Jan 30 '26 06:01

James Michael Hare


Yes, and you can even do this:

public dynamic InstantiateAsStringOrDouble() { return 0.5; }

or

public dynamic InstantiateAsStringOrDouble() { return "hello"; }

and it will work as expected.

like image 27
mellamokb Avatar answered Jan 30 '26 06:01

mellamokb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!