When should one use nullable types in c#?

ACP picture ACP · Apr 13, 2010 · Viewed 17.8k times · Source

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?

Answer

Adriaan Stander picture Adriaan Stander · Apr 13, 2010

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.