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!

3
  • How would you want that to decide which Print to call? I think you'd be better off reading more about dynamic. Commented Apr 29, 2011 at 18:41
  • at runtime, of course. Thanks for your advice, I'm doing that already! :-) Commented Apr 29, 2011 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. Commented Apr 29, 2011 at 19:00

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.
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.

1 Comment

And of course, public dynamic ... { return true; } will probably not work.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.