#210 – Checking to See Whether a Nullable Object Has a Value

Both the built-in nullable types (e.g. int?) and any Nullable<T> types that you use have a HasValue property that lets you determine whether a particular nullable object has a value or not.

  • HasValue is true if the object has a value of the corresponding type
  • HasValue is false if the object has a null value

For example, if you are using a nullable int:

            int? herAge = null;

And you later want to see if this variable has a value (of type int), you can do this:

            if (herAge.HasValue)
                Console.WriteLine("She is {0} yrs old", herAge);

HasValue is useful in cases when you want to perform an operation on an object, where the operation is only valid if the object is non-null.

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 43 other followers