Frequently Asked Interview Questions

Nullable Types in C#

Nullable Type - A value type variable can have null value assigned to it.

C# allows the code to declare and initialize the x and y variables to be written using question-mark notation:

Int32? x = 5;
Int32? y = null;

The following code shows examples of these:

private static void ConversionsAndCasting()

{
      // Implicit conversion from non-nullable Int32 to Nullable<Int32>
      Int32? a = 5;
      // Implicit conversion from 'null' to Nullable<Int32>
      Int32? b = null;
     // Explicit conversion from Nullable<Int32> to non-nullable Int32
      Int32 c = (Int32)a;
     // Casting between nullable primitive types
     Double? d = 5; // Int32->Double? (d is 5.0 as a double)
     Double? e = b; // Int32?->Double? (e is null)
     Console.WriteLine("b.hasValue() " + b.HasValue);
     Console.WriteLine("b.GetValueOrDefault() " + b.GetValueOrDefault());
     Console.WriteLine("a.Value " + a.Value);
}

HasValue : Boolean property tells whether a variable has any values assigned to it ot not.
Value : returns the value of nullable type.
GetValueOrDefault() : Returns the Value if values NULL then it returns default value as 0.

We can also apply operators to nullable instances.

Why we need nullable Value types?

A variable of a value type can never be null; it always contains the value type’s value itself.

For example:
 Working with database data by using the Microsoft .NET Framework can be quite difficult because in the common language runtime (CLR), there is no way to represent an Int32 value as null.

 Java, the java.util.Date class is a reference type, and therefore, a variable of this type can be set to null. However, in the CLR, a System.DateTime is a value type, and a DateTime variable can never be null. If an application written in Java wants to communicate a date/time to a Web service running the CLR, there is a problem if the Java application sends null because the CLR has no way to represent this and operate on it.


Most Visited Pages

Home | Site Index | Contact Us