Null C#

What are NULL and Nullable Types in C#

 The C# compiler forbids you from giving a variable a null value. As a result, C# 2.0 has a specific feature known as the Nullable type that allows you to give a null value to a variable. You can give a variable’s variable a null value by using the Nullable type. Introduced in C# 2.0, nullable types can only interact with Value Types and not with Reference Types.

To explicitly declare whether a reference type can or cannot carry a null value, the nullable types for Reference Type were added later in C# 8.0 in 2019. This enabled us to address the NullReferenceException problem without the use of conditionals. The subject in this article centers on the nullable types for value types.

A System instance is a Nullable type. T-based nullable struct. In this instance, T is a type that includes non-nullable value types like integer, floating-point, boolean, etc. For instance, you can store null values or values between -2147483648 and 2147483647 in an integer type nullable.

Null Syntax

Nullable<data_type> variable_name = null;

The C# nullable data type is represented by the aforementioned syntax. The term “nullable” refers to the System instance-based nullable type. T stands for non-nullable value types like Boolean, integer, floating-point, etc. in the NullableT>struct. The variable name is assigned a null value and represents the variable’s name while the data type indicates the variable’s data type.

Or you can use a shortcut that combines the data type with the? operator.

datatype? variable_name = null;

Example:

// This will result in a compilation error. 
int j = null; 

// True declaration
Nullable<int> j = null; 

// True declaration
int? j = null;

Is There a Difference Between Nullable<T> and ? Annotation?

Both “NullableT>” and “?” are equivalent. ‘NullableT>’ is abbreviated as ‘?’.

The “NullableT>” type is merely a wrapper around the real value, which, unless otherwise defined, will always contain null values. It won’t act differently from the underlying type because it isn’t a new type.

How Can I Get the Value of a Variable of the Nullable Type?

The Nullable type’s value is not directly accessible. If the value is not null, you must use the GetValueOrDefault() function to retrieve the original value. If it is null, you will receive the default value. Zero will be the default value for null.

Example:

// C# example program for Nullable Types 
using System;
class Geeks {
// Main Method static void Main(string[] args) { // specifying the Nullable type Nullable<int> n = null; // using the method // output will by default be 0. // value of null is 0 Console.WriteLine(n.GetValueOrDefault()); // specifying the Nullable type int? n1 = null; // using the method // output will by default be 0. // value of null = 0 Console.WriteLine(n1.GetValueOrDefault());
// specifying the Nullable type as syntax // to define non-nullable int? n2 = 47; // using the method Console.WriteLine(n2.GetValueOrDefault()); // specifying the Nullable type as syntax // to define non-nullable Nullable<int> n3 = 457; // using the method Console.WriteLine(n3.GetValueOrDefault()); } }

Result: 

0
0
47
457

Characteristics of Nullable Types in C#

 

  • The nullable type’s values cannot be accessed directly. If it is not assigned to null, the GetValueOrDefault() method is called to retrieve the assigned value; otherwise, the default value of zero is returned.
  • A nullable type can be used to assign a null value to a variable without the need to first establish a nullable type based on the reference type.
  • Nullable types can have values set to them.
  • You may check the value using Nullable HasValue and Nullable. When an object is given a value, true is returned; when an object is given null, false is returned. A compile-time error is raised if the object has no value allocated to it.
  • Nullable types can be used with the == and! operators.
  • The GetValueOrDefault(T) method returns the assigned value or the default value that was set as default if the nullable type is assigned null.
  • The value of the nullable type can also be assigned a value using the null-coalescing operator (??).
  • Nullable types do not support nested nullable structures.
  • Var type is not supported by a nullable type. If nullable is utilized with var, the compiler issues a Compile-Time Error.

How to Determine if a Value Type is Nullable

It is not simple to recognize a nullable value type at runtime. Use Nullable to see if a given instance belongs to a nullable value type, a function called Nullable.GetUnderlyingType(Type nullableType) method.

Returning null from GetUnderlyingType. yields the Nullable type’s underlying type if not.

Apply the extension approach. Use the following extension method to make it simple to check for nullable value types:

public static bool IsOfNullableType<T>(this T _)
{
    Type type = typeof(T);
    return Nullable.GetUnderlyingType(type) != null;
}
int? num = null; 
Console.WriteLine(num.IsOfNullableType()); // True

Don’t Use Object.GetType

Never depend on the Object. Use the GetType function to check if a specific object is a nullable value type. Requesting the object An instance of a nullable value type that is boxed to Object by the GetType function. The underlying type is represented by the Type returned by GetType when boxing a value of a non-null instance of a nullable value GetType.

Don’t Use  ‘is’ Operator

A nullable value type cannot be found using the “is” operator. If an instance belongs to the provided type, the is operator returns true; otherwise, it returns false. In contrast, an instance of a nullable value type can either be of the specified type or nullable.

Nullable Type’s Benefits in C#

  • Database applications employ nullable types. A nullable type can be used to assign null values to a column in a database that needs them.
  • Nullable types can be used to represent undefined values.
  • Instead of utilizing a reference type, a nullable type can be used to hold a null value.

Helper Class for Null

Since null has a lower value than any other value, comparison operators cannot be used with null; instead, we use the static class nullable. As a helper class for Nullable types, it is seen as useful. The static class that is nullable has a method called GetUnderlyingType. This function returns the type argument of the nullable types.

Nullable Type in C# Operation

Value types, such as numbers, are examples of primitive data types. Even if they are not explicitly initialized when they are defined, value types are saved in the stack and implicitly initialized to their default values by the.NET framework. For instance, a Boolean variable is initially set to false by default, but an integer value is initialized to zero by default. Likewise, default values are represented by all value types. None of them can accurately represent null values, despite the fact that database applications frequently use null values and that doing so is crucial. Any value chosen to represent the null value may not be within the authorized range for the data type of the value. If we chose -1 to represent null for a value type, for instance, -1 might not be an acceptable value for that data type. Additionally, one must ensure that the value chosen to represent the null value in an application is never used for any other purposes within the application. The nullable type was made available by C# 2.0 to address this problem. The organization of the System. The following are examples of nullable types that can be used to define them:

Code:

namespace System
{
  public struct Nullable : System.IComparable, System.INullableValue
{
  public Nullable(V value);
  public static explicit operator V(V? value);
  public static implicit operator V?(V value);
  public V Value { get; }
  public bool HasValue { get; }
  public V GetValueOrDefault();
}
}

Here, the structure accepts a single parameter, and the letter T stands for value type. The syntax can be used to define any value as a nullable type.

Lifted Operators

The corresponding nullable value type T? supports the predefined unary and binary operators as well as any overloaded operators that are supported by a value type T. When one or both operands are null, these operators, also referred to as lifted operators, produce null; otherwise, the operator calculates the result using the contained values of its operands. For instance:

int? e = 10;
int? r = null;
int? t = 10;
e++; // e is 11
e = e * t; // e is 110
e = e + r; // e is null

If one or both operands are null for the comparison operators, >, =, and >=, the result is false; otherwise, the operands’ contained values are compared. Never assume that just because one comparison (like =) returns false, the corresponding comparison (>) will as well. The example below demonstrates that 10 is

  • neither more nor less than zero
  • nor more than zero

int? i = 10;
Console.WriteLine($"{i} >= null is {i >= null}");
Console.WriteLine($"{i} < null is {i < null}");
Console.WriteLine($"{i} == null is {i == null}");
// Output:
// 10 >= null is False
// 10 < null is False
// 10 == null is False
int? q = null;
int? w = null;
Console.WriteLine($"null >= null is {q >= w}");
Console.WriteLine($"null == null is {q == w}");
// Output:
// null >= null is False
// null == null is True

If both operands are null for the equality operator ==, the result is true; if only one operand is null, the result is false; otherwise, the operands’ contained values are compared.

When using the inequality operator!=, the result is false if both operands are null, true if only one operand is null, and else the operands’ contained values are compared.

If a user-defined conversion between two value types already exists, it can be applied to the corresponding nullable value types as well.

Lets Take a Lot at Some General Examples:

Example #1

A C# program that displays nullable types when variables have no value

Code:

// a C# program to demonstrate
// the of Nullable types
using System;
class GFG {
  // Main Method
  static public void Main()
  {
    // a is a nullable type
    // and contains a null value
    int ? a = null;
    // b is a nullable type int
    // and behave as a normal int
    int ? b = 2345;
    // this will not print
    // anything on the console
    Console.WriteLine(a);
    // gives 2345 as output
    Console.WriteLine(b);
  }
}

Output:

0
0
200
10

Example #2

To demonstrate the use of nullable, a C# program is used. Method HasValue.

Code:

using System;
public class GFG {
  //Defining Main Method
  public static void Main()
  {
    // creating a nullable type for the variable e and giving it a value
    Nullable<int> e = 100;
    // the value of the variable e is checked
    Console.WriteLine(e.HasValue);
    // creating a nullable type for the variable I and giving it a value
    Nullable<int> i = null;
    // check the value of the object
    Console.WriteLine(i.HasValue);
  }
}

Output:

True
False

Conclusion

In this tutorial, we first define the idea of a nullable type before learning how it actually functions. Then, we comprehend how various C# programs that use nullable types operate and how their output snapshots are integrated with the programs’ output results.