3

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!

Vishal Seth
  • 4,948
  • 7
  • 26
  • 28
  • How would you want that to decide which Print to call? I think you'd be better off reading more about `dynamic`. – David Heffernan Apr 29 '11 at 18:41
  • at runtime, of course. Thanks for your advice, I'm doing that already! :-) – Vishal Seth Apr 29 '11 at 18:57
  • 1
    It does work, but be careful with dynamic. It can solve a lot of issues and simultaneously give you a lot of headaches :-) basically you gain runtime flexibility but lose all compiler time checking. – James Michael Hare Apr 29 '11 at 19:00

2 Answers2

3

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.

James Michael Hare
  • 37,767
  • 9
  • 73
  • 83
  • Thanks James. The code I'm trying to convert has 3-4 levels deep method calls with passing boxed Object parameters. I thought of writing overloaded methods but its like some if-else logic, then a method call, more if-else logic than another method call (passing the same Object parameter it gets from 2-3 levels up)....Pain in the neck sort of legacy code. Somewhere down the bottom it checks if the Object is ArrayList or HashTable or blah blah and acts accordingly. – Vishal Seth Apr 29 '11 at 19:08
2

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.

mellamokb
  • 56,094
  • 12
  • 110
  • 136