65.9K
CodeProject is changing. Read more.
Home

Converting a nullable object to an integer

starIconstarIconstarIconstarIconstarIcon

5.00/5 (4 votes)

Mar 19, 2011

CPOL
viewsIcon

21333

As of .NET 2.0, we have a built-in way[^] of converting a Nullable<T> object to an object of type T with a default::

int? a;
int b = a.GetValueOrDefault(-1);

So to converting an object to an integer would then be:

object someValue = null; // Can be anything
int convertedInteger = ((int?)someValue).GetValueOrDefault(-1);