Junior — Middle
What is the role and application of a data type that allows storing null values?
sobes.tech AI
Answer from AI
In C#, data types that can hold null values are called Nullable types and are denoted with a question mark, for example, int?. They allow a variable to hold either a value of its base type or null, which is useful for representing absence of data or undefined state.
Application:
- Working with databases where fields can be empty.
- Handling optional parameters.
- Improving code readability and safety by explicitly indicating that a variable may not have a value.
Example:
int? age = null;
if (age.HasValue)
{
Console.WriteLine($"Age: {age.Value}");
}
else
{
Console.WriteLine("Age is not specified");
}