InterviewSolution
Saved Bookmarks
| 1. |
How to use Nullable Types in .NET? |
|
Answer» As we know we cannot assign the null value to any value type so for that we use nullable type where we can assign null value to the value type variables. Syntax: Nullable<T> where T is a type. Nullable type is an instance of System.Nullable<T> STRUCTNullable Struct : [Serializable] public struct Nullable<T> where T : struct { public bool HasValue { get; } // it will return true if we assigned a value, if there is no value or if we assign a null value it will return false; public T Value { get; } } HasValue : static void Main(STRING[] args) { Nullable<int> i = null; if (i.HasValue) Console.WriteLine(i.Value); else Console.WriteLine("Null"); }Example: [Serializable] public struct Nullable<T> where T : struct { public bool HasValue { get; } public T Value { get; } } static void Main(string[] args) { Nullable<int> i = null; if (i.HasValue) Console.WriteLine(i.Value); // or Console.WriteLine(i) else Console.WriteLine("Null"); }Output: NullIt will check WHETHER an object has been assigned a value if it is having null value it will return false and the else PART will be executed. To get the value of i using the nullable type you have to use GetValueOrDefault() method to get the ACTUAL value. static void Main(string[] args) { Nullable<int> i = null; Console.WriteLine(i.GetValueOrDefault()); } |
|