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
What's the difference between the debug class and trace class? Documentation looks the same.
Write a program to create a user control with name and surname as data members and login as method and also the code to call it. (Hint use event delegates) Practical Example of Passing an Events to delegates
What are custom exceptions?
What operators can be used to cast from one reference type to another without the risk of throwing an exception?
What is object array in c#?
What is cts, clr?
What does dbml mean?
What is array collection?
How to reverse each word in a string using c#?
what is the meaning of Object lifetime in OOPS
What are the fundamental differences between value types and reference types?
What is a static field?
What is polymorphism c# example?
What is namespace explain with example?
What does == mean in c sharp?