Isaac Lyman
Isaac Lyman

Reputation: 2201

Why can C#'s System.Convert convert (string) to (int), but not (string) to (int?)?

If I run the following code:

(int)Convert.ChangeType("3", typeof(int))

The result is 3. Awesome.

If I change it to:

(int?)Convert.ChangeType("3", typeof(int?))

The result is

Invalid cast from 'System.String' to 'System.Nullable`1 [[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]'.

However, it handles this just fine:

(int?)Convert.ChangeType("3", typeof(int))

Why can't it handle the conversion to a nullable int type directly?

Upvotes: 0

Views: 348

Answers (1)

Luaan
Luaan

Reputation: 63772

Convert.ChangeType long predates nullable values in .NET, so it couldn't have been a hack. There's very little reason to use Convert nowadays.

Why is this a hack? Well, you're asking Convert to perform multiple conversions in a row, while also realizing that a wrong value should be represented as null in the "real" return value. Multiple implicit conversions never happen in .NET. int and int? are completely separate types, and it's only the C# compiler that makes you think they work well together - it's all just syntax sugar. Syntax sugar doesn't work when you're just calling a random method that returns object :)

If you need this functionality, just write your own wrapper that always returns a nullable.

Upvotes: 5

Related Questions