Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does string.Format handle null values?

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?

like image 560
Martin Avatar asked Nov 07 '12 19:11

Martin


People also ask

What happens if you use NULL value in string interpolation?

If the interpolation expression evaluates to null , an empty string ("", or String.

Can string contains null?

An empty string is a String object with an assigned value, but its length is equal to zero. A null string has no value at all. A blank String contains only whitespaces, are is neither empty nor null , since it does have an assigned value, and isn't of 0 length.

What is string format () used for?

In java, String format() method returns a formatted string using the given locale, specified format string, and arguments. We can concatenate the strings using this method and at the same time, we can format the output concatenated string.


1 Answers

I'm guessing here, but it looks to be the difference of which overloaded call you're hitting; String.Format has multiple.

In the first example, it would make sense you're hitting String.Format(string,object).

In the second example by providing null you're most likely hitting String.Format(string,params object[]) which, per the documentation, would raise an ArgumentNullException when:

format or args is null.

If you're running .NET4, try using named parameters:

String.Format("Another exception occured: {0}", arg0: null); 

Why is it hitting the params object[] overload? Probably because null isn't an object, and the way params works 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:

String.Format("Hello, {0}! Today is {1}.", "World", "Sunny"); String.Format("Hello, {0}! Today is {1}.", new Object[]{ "World", "Sunny" }) 

So it's translating your statement call to something along the lines of:

String format = "Another exception occured: {0}"; Object[] args = null; String.Format(format, args); // throw new ArgumentNullException(); 
like image 170
Brad Christie Avatar answered Sep 20 '22 17:09

Brad Christie