Nullable Type in C#

Nullable type in C#
We can declare a variable as nullable when we want to know that a value has been assigned to that variable or not. Declaring a variable as nullable enables the HasValue and Value members. We can use the HasValue property on the variable to check if the value has been assigned to the variable.

Example of Using Nullable
Let’s take an example of boolean variable. As we know the default value for a boolean variable is false. But we want that we should be able to know if user has selected true or false. So we define the bool variable as nullable like this:

Nullable<bool> testVariable= null;

Now we have the testVariable as a boolean variable having a value of null. Now when use the properties like this :

if(testVariable.HasValue)
MessageBox.Show(String.Format("Value is {0}",testVariable.value )); 

kick it on DotNetKicks.com

Shout it

pimp it

Anky Goyal

I am MCPD certified in .NET and working on .NET technologies for past 3yrs. I am very passionate about the new features which get introduced in the technology. I am here to share the new features i get to know in the world of Microsoft. Follow me on twitter @ankygoyal [email protected]Ankit Goyal

More Posts - Website