Question

I have this code :

static dynamic Mean (dynamic x, dynamic y)
{
  return (x + y) / 2;
}


static void Main()
{
  int x = 3, y = 5;
  Console.WriteLine (Mean (x, y)); //this is working
}

however the following line failes at runtime :

string s = Mean (3, 5); // Runtime error!

why is that ?

why s can not be set with the dynamic value ?

and if so , why Console.WriteLine (...) did succeed to run with this dynamic value ?

edit

and if if so , how can i make string s = Mean (3, 5); work ?

Was it helpful?

Solution

Because in this case you're trying to set int value to your string variable.

Console.WriteLine automatically do .ToString() before writing in console. Try this for example.

int x=5;
Console.WriteLine(x);

OTHER TIPS

your code would have to be valid if written statically.

using dynamic simply means that the type checking is deferred until runtime. In your case mean is returning an int. You are therefor trying to assign an int to a string which is not legal.

typewise there not difference between your code and one using the below implementation of mean

int Mean(int x, int y){
   return (x+y)/2;
}

the statement below would result in a compilation error

string s = Mean(3,5);

by using dynamic as return type and the type for x and y, you've simply told the compiler not to check the types but to leave the type checking to the runtime. The check is essentially the same in your sample code as the one performed by the compiler and the result is also the same. The assignment is illegal.

Console.WriteLine has an overload that takes an int so the type checking succeeds and all is well in that case

Console.WriteLine calls the ToString() method on an object. At runtime when you call ToString() on the dynamic object, which is a int, there is no issue. However, in your second example you are essentially trying to put a int into a string, which is why it is complaining.

I believe this would allow you to do what you want.

string s = (Mean (3, 5)).ToString();
dynamic s = Mean (3, 5); 

or

var s = Mean(3, 5);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top