Covers topics on the Microsoft Certification Exam for the .NET Framework (Exam 70-536, Microsoft .NET Framework - Application Development Foundation)

Wednesday, March 5, 2008

What is the correct declaration for a nullable integer?

Nullable was added in .NET 2.0. Nullable allows value data types to have an additional pattern, null. This can be useful to indicate within your code that a variable has not been initialized. For example, since we are talking about integers, before nullable was available an integer might be given a value of zero or some negative number when it was initialized. But what if zero or negative numbers are valid patterns? You can't really say that if a number is zero it is because it wasn't initialized or because that is the actual value.

Now that we have seen a reason for having nullable, it is time to answer the actual question. There are two ways to declare a nullable integer, the long form and the short form. (Examples will be provided for both C# and Visual Basic)

Long Form

' VB
Dim i As Nullable(Of Integer) = Nothing

// C#
Nullable<int> i = null;

Short Form (C# only)

//C# shorthand
int? i = null;

Additional Resources
Nullable Structure in VisualBasic (Microsoft)
Nullable Type in C# (Microsoft)

No comments:

Support This Site

LinkShare  Referral  Prg