Click here to Skip to main content
15,868,141 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

Converting a nullable object to an integer

Rate me:
Please Sign up or sign in to vote.
5.00/5 (4 votes)
19 Mar 2011CPOL 19.5K   2   5

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);

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer Repstor Ltd
United Kingdom United Kingdom
I am a Product Architect at Repstor.

Repstor custodian and Repstor Provisioning Engine provide case management and provisioning for SharePoint.

Repstor affinity provides uninterrupted access to content systems, like SharePoint through the familiar interface of Microsoft Outlook.

Comments and Discussions

 
GeneralReason for my vote of 5 Nice work Pin
Kelvin Armstrong23-May-11 20:54
Kelvin Armstrong23-May-11 20:54 
GeneralReason for my vote of 5 thanks a lot! Pin
DRiVe-X-S23-May-11 19:31
DRiVe-X-S23-May-11 19:31 
GeneralReason for my vote of 5 I didn't know about that function. I... Pin
AspDotNetDev19-Mar-11 10:37
protectorAspDotNetDev19-Mar-11 10:37 
GeneralI would agree that it's neater, but not everyone is familiar... Pin
Jonathan Cardy19-Mar-11 6:54
Jonathan Cardy19-Mar-11 6:54 
GeneralI think the first alternate is a neater way to do the same s... Pin
Eduard Keilholz19-Mar-11 5:39
Eduard Keilholz19-Mar-11 5:39 
I think the first alternate is a neater way to do the same since the code is easier to read and maintain. Even though, thanks for sharing!

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.