Ads

C# Programming 18 - What is Nullable types?

Hello All,

In this article we will learn about Nullable types.



Normally Null values are supported in Reference Types, like string, objects datatypes. But nullable keyword allows value types (such as int, float, bool, etc.) to have a null value.

To use nullable in C#, we can append a "?" after the value type when declaring a variable. 

For example:

int? nullableInteger = null;
float? nullableFloating = 3.142f;
bool? nullableBoolean = true;

In the example above, nullableInteger  has a value of null, while nullableFloating has a value of 3.142f, and nullableBoolean has a value of true. You can also use the Nullable<T> struct to create nullable value types:

Nullable<int> nullableInteger = null;
Nullable<float> nullableFloating = 3.142f;
Nullable<bool> nullableBoolean = true;

How can I check, value type(int,float,bool) has value or null?

To check whether a nullable value type has a value or null,we can use the HasValue property, below is the simple example.

if (nullableInteger.HasValue)
{
    int intValue = nullableInteger.Value;
    Console.WriteLine("The value of nullableInteger is " + intValue);
}
else
{
    Console.WriteLine("nullableInteger is null");
}

In the above example, if nullableInteger has a value, it is assigned to intValue and printed to the console. If nullableInteger is null, then a message is printed indicating that it is null.

You can also use the null-coalescing operator (??) to provide a default value for a nullable value type if it is null.

int nonNullableInteger = nullableInteger ?? 0;

I hope you understood this article, Will see you in new article. Until then take care bye see you.

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !