Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert.ToInt32(String) on String.Empty vs. Null [duplicate]

Tags:

The expression Convert.ToInt32(String.Empty) will raise a FormatException because it cannot parse an empty string into an Int32 value.

However, the expression Convert.ToInt32(DirectCast(Nothing, String)) in VB.NET or Convert.ToInt32((string)null) in C# will parse the null to an Int32 value of zero.

Digging into the .NET source in Convert.cs, I see the following code:

public static int ToInt32(String value) {     if (value == null)          return 0;     return Int32.Parse(value, CultureInfo.CurrentCulture); } 

This explains the behaviour, but I'd like to understand why it was written this way, instead of returning a zero for an empty string as well?

For example, why wasn't it written as:

public static int ToInt32(String value) {     if (String.IsNullOrEmpty(value))          return 0;     return Int32.Parse(value, CultureInfo.CurrentCulture); } 

(Note that String.IsNullOrEmpty() and Convert.ToInt32() both date back to .NET 2.0, possibly earlier.)

Edit: My question is very similar to this question, but I'd also like to know why Convert.ToInt32(String.Empty) raises an exception instead of returning the Int32 default value of 0. (The answer being that String.Empty is not the default value of String, so there's no correlation.)

like image 303
MCattle Avatar asked Feb 12 '13 20:02

MCattle


1 Answers

I have absolutely no insight into the actual design team's reasoning behind this, but it seems to me that it might be some sort of "default value equivalency". Null is the default value of string, so it seems logical to convert it to a default value of int. String.Empty is however a string like any other non-null string data, so it is expected to be formatted, hence the exception.

I think ArgumentNullException would have been a "cleaner" decision, but I don't know whatever internal issues may be behind this all...

Another edit:
There, right in the MSDN documentation, one of the 5 possible outcomes:

A successful conversion. For conversions between two different base types not listed in the previous outcomes, all widening conversions as well as all narrowing conversions that do not result in a loss of data will succeed and the method will return a value of the targeted base type.

It seems the conversion from null object to another type has no reason to fail (not a format error, not an unsupported type conversion), but a value type such as int has no representation of "no data", so a default value of the target type is produced.

A quick thought - the "opposite" conversion, Convert.ToString(0), does not yield null because:

  • 0 is data, it can be very valid and important value in many cases
  • null is not a correct string representation of 0
like image 71
Honza Brestan Avatar answered Oct 23 '22 04:10

Honza Brestan