Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When should one use nullable types in c#?

Tags:

c#

nullable

I have been repeatedly asked the following questions in many interviews.... But still can't explain them with a simple example...

  1. What are nullable types in c#?
  2. When should one use nullable types in c#?
  3. Can you give a simple example?

Any suggestions?

like image 378
ACP Avatar asked Apr 13 '10 05:04

ACP


People also ask

Why do we need nullable types?

We are using nullable types when we need to represent an undefined value of an underlying type. While Boolean values can have either true or false values, a null in this case means false as there is no undefined value. When you have a database interaction, a variable value can be either undefined or missing.

Where do we use Nullable type?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.

When should nullable types be used in C#?

The Nullable type allows you to assign a null value to a variable. Nullable types introduced in C#2.0 can only work with Value Type, not with Reference Type. The nullable types for Reference Type is introduced later in C# 8.0 in 2019 so that we can explicitly define if a reference type can or can not hold a null value.

Should I use null in C#?

In C#, you can assign the null value to any reference variable. The null value simply means that the variable does not refer to an object in memory. You can use it like this: Circle c = new Circle(42); Circle copy = null; // Initialized ... if (copy == null) { copy = c; // copy and c refer to the same object ... }


1 Answers

From Using Nullable Types (C# Programming Guide) (Link updated circa 2018)

For an example of when you might use a nullable type, consider how an ordinary Boolean variable can have two values: true and false. There is no value that signifies "undefined". In many programming applications, most notably database interactions, variables can exist in an undefined state. For example, a field in a database may contain the values true or false, but it may also contain no value at all. Similarly, reference types can be set to null to indicate that they are not initialized.

like image 69
Adriaan Stander Avatar answered Sep 21 '22 06:09

Adriaan Stander