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.)
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:
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