1 / 2

How to Work with Nullable Types in C#

Learn how to use nullable in C#

Download Presentation

How to Work with Nullable Types in C#

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Want to learn about how to work with Nullable types in C#? In C# language, there are majorly two types of data types Value and Reference type. We can not assign a null value directly to the Value data type, therefore, C# 2.0 provides us the Nullable types to assign a value data type to null. What is Nullable types? As described above, the Nullable types used to assign the null value to the value data type. That means we can directly assign a null value to a value data type attribute. Using Nullable<T>, we can declare a null value where T is a type like int, float, bool, etc. Nullable types represent the Null value along with the actual range of that data type. Like the int data type can hold the value from -2147483648 to 2147483647 but a Nullable int can hold the value null and range from -2147483648 to 2147483647

  2. How to declare Nullable types There are two ways to declare Nullable types. Nullable<int> example; OR int? Example; Properties of Nullable types Nullable types have two properties. ● ● HasValue Value HasValue: ​This property returns a value of bool depending on whether or not the nullable variable has a value. If the variable has a value, it returns true; otherwise, if it has no value or is null, it returns false. Nullable<int> a = null; Console.WriteLine(a.HasValue); // Print False Nullable<int> b = 9; Console.WriteLine(b.HasValue); // Print True Value:​ The value of the variable Nullable form is given by this property. If the variable has any value, the value will be returned; else, it will give the runtime InvalidOperationException exception when the variable value is null. Nullable<int> a = null; Console.WriteLine(a.Value); // Gives run time exception of type 'InvalidOperationException' Nullable<int> b = 9; Console.WriteLine(b.Value); // Print 9 You can read more about method of Nullable types and rules of using Nullable types in this blog here: How to work with Nullable types in C#

More Related