.NET Tips and Tricks

Blog archive

Accepting Nullable Data

Sometimes you get null or Nothing passed to parameters for methods in your application. Sometimes that's not OK, but sometimes it is -- especially if you're accepting data from a database. If you're accepting a value parameter (like an integer), you may have been declaring your parameters as object so that you accept nulls. There is a better solution: you can add a question mark to your type declaration to indicate that it's OK to pass a null/Nothing value to that parameter:

Sub AcceptingParms(parmNullsOK As Integer?)

  If parmNullsOK IsNot Nothing Then

  Else

  End If

End Sub

You're not limited to using the question mark in parameters or with the Integer/int datatype. You can use it on any value type where you're willing to accept a null/Nothing value. Do be aware, though, that these nullable types are a different datatype from their non-nullable cousins (i.e. int? is not int and Integer? is not Integer). So if you want to use a nullable value with a non-nullable value, you'll have to do a conversion:

Dim res As Integer
Dim num? As Integer = 2
res = Integer.Parse(num) + Integer.Parse(num)

What you're actually doing when you add the question mark to the end of your datatype is creating an instance of a reference class called System.Nullable<T>. To put it another way, int? is the same as System.Nullable<int>). The question mark is just shorthand for the longer declaration.

Posted by Peter Vogel on 06/07/2011 at 1:16 PM


comments powered by Disqus
Upcoming Events

.NET Insight

Sign up for our newsletter.

I agree to this site's Privacy Policy.