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?
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.
The +
operator here is concatenation, not addition.
Secondly, the +
operator is overloaded for Nullable<T>
in a way that doesn't cause NullReferenceException
s.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With