Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is the concatenation of an int and a string not complaining at compile time

Tags:

c#

I have the following in visual studio, and its not complaining:

int? int1;
int? int2;

string str = int1 + "-" + int2;

my guess is this will throw an exception somewhere at runtime, but why is visual studio allowing this? Just because it could be null? Is a null int treated the same way as a null string?

like image 645
duxfox-- Avatar asked May 15 '15 19:05

duxfox--


2 Answers

There are a number of overloads to the + operator, two of them are:

operator + (string s, object o)
operator + (object o, string s)

The effect of this is that you can "add" an object of any type to a string.

The implementation of the overload will use ToString to get a string representation of that object and concat it with the string. However, it will treat any null object (or strings) as if they're an empty string, and not throw an exception at runtime.

Note that, as a result of passing an int? to an object it will result in the value being boxed, because it's a struct, and there's special support for boxing Nullable<T> such that if HasValue is false (i.e. it logically represents a null value) it boxes null rather than boxing a Nullable that represents null.

like image 67
Servy Avatar answered Oct 19 '22 04:10

Servy


The + operator here is concatenation, not addition.

Secondly, the + operator is overloaded for Nullable<T> in a way that doesn't cause NullReferenceExceptions.

However your code won't compile because you haven't set int1 and int2 to a value. However if you use null, then the code the string result will be just "-".

Here is a CodingGround project with your code and it outputs just "-": http://goo.gl/sHMqk4

like image 5
Dai Avatar answered Oct 19 '22 04:10

Dai