Click here to Skip to main content
14,367,615 members

Converting a nullable object to an integer

Rate this:
5.00 (4 votes)
Please Sign up or sign in to vote.
5.00 (4 votes)
19 Mar 2011CPOL
Here is a slightly shorter version of your first conversion:object someValue = 1;int result = someValue as int? ?? -1;
Here is a slightly shorter version of your first conversion:
object someValue = 1;
int result = someValue as int? ?? -1;


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


About the Author

Web Developer
United States United States

  • Managing Your JavaScript Library in ASP.NET (if you work with and you don't read that, you are dead to me).
  • Graduated summa cum laude with a BS in Computer Science.
  • Wrote some articles and some tips.
  • DDR ("New high score? What does that mean? Did I break it?"), ping pong, and volleyball enthusiast.
  • Software I have donated to (you should too):

Comments and Discussions

Questionalways get null Pin
taleofsixstrings27-Sep-13 18:38
membertaleofsixstrings27-Sep-13 18:38 
AnswerRe: always get null Pin
AspDotNetDev28-Sep-13 16:14
protectorAspDotNetDev28-Sep-13 16:14 
Works for me. I ran the following Windows Forms application and was shown a value of "1" in the message box:
using System;
using System.Windows.Forms;

namespace WindowsFormsApplication1
    public partial class Form1 : Form
        public Form1()

        private void Form1_Load(object sender, EventArgs e)
            object someValue = 1;
            int result = someValue as int? ?? -1;

GeneralDon't confuse devs by using "int? ?? -1" instead use some pa... Pin
Kunal Chowdhury «IN»16-May-11 20:10
mentorKunal Chowdhury «IN»16-May-11 20:10 
GeneralRe: Good advice. The code I presented is little more than a nove... Pin
AspDotNetDev16-May-11 20:45
protectorAspDotNetDev16-May-11 20:45 
GeneralThanks for your improvement! I Like your input, and included... Pin
Eduard Keilholz19-Mar-11 6:37
memberEduard Keilholz19-Mar-11 6:37 
GeneralRe: Cool. FYI, I shortened the code further (didn't need parens ... Pin
AspDotNetDev19-Mar-11 11:43
protectorAspDotNetDev19-Mar-11 11:43 

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.

Posted 18 Mar 2011

Tagged as


4 bookmarked