What is Nullable Type in c#

Answer Posted / vishnu

Declare a variable as nullable if you want to be able to
determine whether a value has been assigned. For example, if
you are storing data from a yes/no question on a form and
the use did not answer the question, you should store a null
value. The following code declares a boolean variable the
can be true, false, or null:

`VB
Dim b As Nullable(of Boolean) = Nothing

//C#
Nullable<bool> b = null;

//Shorthand notation, only for C#
bool? b = null;

Declaring a variable as nullable enables the HasValue and
Value members. Use HasValue to detect whether a value has
been set as follows:

`VB
If b.HasValue Then Console.WriteLine(“b is {0}.”, b.Value)
Else Console.WriteLine(“b is not set”);

//C#
If (b.HasValue)
Console.WriteLine(“b is {0}.”, b.Value);
Else
Console.WriteLine(“b is not set.”);

----------------------------

Exmaple:
class NullableExample
{
static void Main()
{
int? num = null;
if (num.HasValue == true)
{
System.Console.WriteLine("num = " + num.Value);
}
else
{
System.Console.WriteLine("num = Null");
}

//y is set to zero
int y = num.GetValueOrDefault();

// num.Value throws an InvalidOperationException if
num.HasValue is false
try
{
y = num.Value;
}
catch (System.InvalidOperationException e)
{
System.Console.WriteLine(e.Message);
}
}
}

Is This Answer Correct ?    1 Yes 1 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What is difference between private and protected in c#?

487


What are sorted lists?

496


What is dataset c#?

485


What is an icollection in c#?

487


What is a must for multitasking

559






What is gac? How to put assembly in gac?

547


What is difference between il and dll ?

523


How to override a function in c#?

538


When a Static Constructor is called in a Class?

575


What are indexers in c# .net?

519


What is a template class?

484


How can you access a private method of a class?

504


How do you implement thread synchronization in c#?

454


What are the Configuration files in .net?

509


What is default method in c#?

496