In the following code below, why do the two string.Format calls not behave the same way? In the first one, no exception is thrown, but in the second one an ArgumentNullException is thrown.
static void Main(string[] args)
{
Exception e = null;
string msgOne = string.Format("An exception occurred: {0}", e);
string msgTwo = string.Format("Another exception occurred: {0}", null);
}
Could someone please help me understand the difference between the two?
I’m guessing here, but it looks to be the difference of which overloaded call you’re hitting;
String.Formathas multiple.In the first example, it would make sense you’re hitting
String.Format(string,object).In the second example by providing
nullyou’re most likely hittingString.Format(string,params object[])which, per the documentation, would raise anArgumentNullExceptionwhen:If you’re running .NET4, try using named parameters:
Why is it hitting the
params object[]overload? Probably becausenullisn’t an object, and the wayparamsworks is that you can pass either each value as a new object in the call or pass it an array of the values. That is to say, the following are one in the same:So it’s translating your statement call to something along the lines of: