Null handling in C#

Posted on 2011-05-12
Last Modified: 2012-05-11

I have a problem. My stored procedure produces an integer values which I am assigning to an Nullable integer variable.

Dataclass where I call my Stored proc
//Typecasting error happens here . Unable to cast from object to integer datatype
userProfile.NS_ID = Convert.ToInt32(dr.ItemArray[41]);

userprofile class

public int? NMLS_ID

NS_ID is should get an integer..based on which I do my own business logic. but it is expected that 99% of time stored proc would be producing a null because my db is fresh and users have not started using it.

How do i handle this.

Question by:SubbuUSA
    LVL 4

    Accepted Solution

    I suppose you are talkinig about MSSQL stored procedure. Then use comparison with DBNull.Value:

    if (o == DBNull.Value)
      // handle null value
    LVL 39

    Assisted Solution

    by:Kyle Abrahams
    In your code that references the class:

    if (ClassInstance.NMLS_ID == null)
       //do nothing or report to user that this is null
       // do something

    If you were only interested in it when there was not a null you could flip the if:

    if (ClassInstance.NMLS_ID != null)
       //  do something

    Author Closing Comment

    Thanks Guys

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    IT, Stop Being Called Into Every Meeting

    Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

    This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
    Entity Framework is a powerful tool to help you interact with the DataBase but still doesn't help much when we have a Stored Procedure that returns more than one resultset. The solution takes some of out-of-the-box thinking; read on!
    Hi everyone! This is Experts Exchange customer support.  This quick video will show you how to change your primary email address.  If you have any questions, then please Write a Comment below!
    Here's a very brief overview of the methods PRTG Network Monitor ( offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    8 Experts available now in Live!

    Get 1:1 Help Now