.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

Featured

  • Project Oqtane Provides Blazor-Based Modern App Framework

    The .NET Foundation recently shined a spotlight on Project Oqtane, a modern application framework for Blazor, Microsoft's red-hot open source project that enables web development in C#.

  • Radzen Open Sources 60+ Blazor Components

    Radzen, a development tooling vendor that provides third-party components for .NET coders, open sourced its controls for Blazor, Microsoft's red-hot open source project that enables web development in C#.

  • Customize Your Own Audio Test Cues in Visual Studio 2019 v16.9 Preview 3

    Yes, developers can be alerted to a failed test with a fart sound.

  • Progress Touts New Third-Party Blazor UI Components

    Third-party dev tool specialist Progress announced an update to its .NET-centric offerings, touting new controls for Blazor, Microsoft's red-hot project for creating web apps with C#.

Upcoming Events