2

For reasons I won't bore you with, I have a generic object whose value is null, and I need to convert it to a nullable int.

object foo = null
int? bar = Convert.ToInt32(foo) // bar = 0
int? bar = (int?)Convert.ToInt32(foo) // bar = 0
int? bar = Convert.ToInt32?(foo) // not a thing

From this thread:

int? bar = Expression.Constant(foo, typeof(int?)); // Can not convert System.Linq.Expression.Constant to int?

I need bar to be null. How do I do this?

Casey Crookston
  • 13,016
  • 24
  • 107
  • 193
  • 2
    `int? bar = (int?)foo;` seems to work for me. – itsme86 Nov 08 '18 at 22:31
  • `Convert.ToInt32()` always returns an `int`, never a `null`. That seems to be the main flaw in your original attempts. If you go to an apple tree, you will **always** get an apple - never an orange. – mjwills Nov 08 '18 at 22:38
  • 4
    I personally would suggest `int? bar = foo as int?;` This is slightly safer than using `(int?)`. – mjwills Nov 08 '18 at 22:39
  • 1
    Possible duplicate of [Better way to cast object to int](https://stackoverflow.com/questions/745172/better-way-to-cast-object-to-int) – mjwills Nov 08 '18 at 22:40

1 Answers1

3

The following will work

int? bar = (int?)foo;

However as pointed out in comments this will throw a Specified cast is not valid exception if foo is anything but a null or an int.

If you prefer just to get a null if the conversion is not valid then you can use

int? bar = foo as int?;

which will hide conversion problems.

Loofer
  • 6,841
  • 9
  • 61
  • 102
  • Beat me to it by seconds. – itsme86 Nov 08 '18 at 22:32
  • 1
    Great minds think alike! Or is it fools seldom differ :D – Loofer Nov 08 '18 at 22:32
  • well now I feel silly. Trying to make things harder than they need to be, I guess – Casey Crookston Nov 08 '18 at 22:35
  • Hold on... :) What if foo is a string? It's typed as `object`, so it has no obligation to be convertible to an `int?`. – Curt Nichols Nov 08 '18 at 22:37
  • For sure you will get a runtime error if `foo` is anything but `null` or an `int`... but all the question asks for is to convert an `object null` to an `int? null`. – Loofer Nov 08 '18 at 23:28
  • What @Loofer said and it might actually be desirable to get a runtime error in that instance where you're expecting an int instead of blindly hiding the error/bug. Obviously circumstance-dependent. – itsme86 Nov 09 '18 at 00:18