Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can dynamic variables treated as "int" overflow?

Tags:

c#

c#-4.0

Suppose you have a dynamic variable being treated as an int (value is less the int.MaxValue).

At some point in your application the dynamic value increases and surpasses the "int" value.

Will the application crash or treat it (convert) as a long?

like image 462
Joseph Avatar asked Feb 22 '11 21:02

Joseph


2 Answers

Suppose you have a dynamic variable being treated as an int (value is less the int.MaxValue).

By "being treated as int" I assume you mean "containing a value of runtime type int".

At some point in your application the dynamic value increases and surpasses the "int" value.

OK. How? You omit the most important part of the question. How did the value increase?

Will the application crash or treat it (convert) as a long?

Sometimes it will crash, sometimes the result will be long, sometimes the result will be double, or decimal, sometimes the int will wrap around. Since you haven't said how it is that the value is being made to increase it is impossible to answer your question.

In general, the rule for dynamic is that the dynamic code will behave at runtime as the equivalent non-dynamic code would have behaved if the compile-time type had been known. If the compiler would have given an error, then the runtime gives an error. If the compiler would have added two ints to produce a third, then the runtime will add two ints to produce a third. If the compiler would have added an int and a double to produce a double, then the runtime will add an int and a double to produce a double. And so on.

like image 193
Eric Lippert Avatar answered Oct 27 '22 03:10

Eric Lippert


Easy to test in LINQPad:

void Main()
{
    dynamic i = int.MaxValue - 10;
    i += 15;
    Console.WriteLine(i.GetType());
    Console.WriteLine(i);
}

Output:

typeof (Int32) 
-2147483644
like image 21
Lasse V. Karlsen Avatar answered Oct 27 '22 04:10

Lasse V. Karlsen