Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

Converting a nullable object to an integer

, 19 Mar 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
As of .NET 2.0, we have a built-in way[^] of converting a Nullable object to an object of type T with a default::int? a;int b = a.GetValueOrDefault(-1);Your example would then be:object someValue = null; // Can be anythingconvertedInteger = ((int?)someValue).GetValueOrDefault(-1);
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);
Your example would then be:
object someValue = null; // Can be anything
convertedInteger = ((int?)someValue).GetValueOrDefault(-1);


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


About the Author

Jonathan Cardy
Software Developer Repstor Ltd
United Kingdom United Kingdom
I am a Software Developer at Repstor.

Repstor’s products enable the successful adoption of content management systems within organizations. Repstor affinity provides uninterrupted access to content systems, like SharePoint through the familiar interface of Microsoft Outlook. Repstor assist provides facilitated filing for all users by suggesting the most suitable location for new content based on best practice filing.
Follow on   Twitter

Comments and Discussions

GeneralReason for my vote of 5 Nice work PinmemberKelvin Armstrong23-May-11 21:54 
GeneralReason for my vote of 5 thanks a lot! PinmemberDRiVe-X-S23-May-11 20:31 
GeneralReason for my vote of 5 I didn't know about that function. I... PinprotectorAspDotNetDev19-Mar-11 11:37 
GeneralI would agree that it's neater, but not everyone is familiar... PinmemberJonathan Cardy19-Mar-11 7:54 
GeneralI think the first alternate is a neater way to do the same s... PinmemberEduard Keilholz19-Mar-11 6:39 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150327.1 | Last Updated 19 Mar 2011
Article Copyright 2011 by Jonathan Cardy
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid