Reputation: 1483
Sorry about my ignorance but I've been trying for a long time without a reasonable explication about this:
Why a +
operator doesn't throw any exception when any parameter is null
;
for example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication4
{
class Program
{
static void Main(string[] args) {
string str = null;
Console.WriteLine(str + "test");
Console.ReadKey();
}
}
}
Upvotes: 2
Views: 85
Reputation: 98868
Because C# compiler translates +
operator to String.Concat
method in your operation and this method uses empty string ""
when you try to concatenate null
.
From documentation;
An Empty string is used in place of any
null
argument.
And from 7.7.4 Addition operator
The binary + operator performs string concatenation when one or both operands are of type string. If an operand of string concatenation is
null
, an empty string is substituted. Otherwise, any non-string argument is converted to its string representation by invoking the virtualToString
method inherited from type object. IfToString
returnsnull
, an empty string is substituted.
Also from reference source;
if (IsNullOrEmpty(str0))
{
if (IsNullOrEmpty(str1))
{
return String.Empty;
}
return str1;
}
Upvotes: 8