Nullable Value Types
Part of the Logic & Flow section of Coddy's C# journey — lesson 32 of 66.
In C#, value types like int, float, and bool cannot normally hold null values. Nullable value types allow these types to represent either a value or null.
Declare a regular int:
int regularNumber = 10;Declare a nullable int using the ? syntax:
int? nullableNumber = 20;Assign null to a nullable type:
nullableNumber = null;After executing the above code, nullableNumber contains no value (null).
Check if a nullable type has a value:
if (nullableNumber.HasValue)
{
Console.WriteLine("Value is: " + nullableNumber.Value);
}
else
{
Console.WriteLine("No value");
}You can also use the null-coalescing operator to provide a default value:
int definiteNumber = nullableNumber ?? 0;Challenge
EasyCreate a method named ProcessNullableAge that:
- Takes a nullable int parameter called
age - Checks if the age has a value
- If it has a value, prints "Age is: X years" (where X is the value)
- If it doesn't have a value, prints "Age not provided"
- Returns the age value if present, otherwise returns 0
Cheat sheet
Nullable value types allow value types like int, float, and bool to represent either a value or null.
Declare a nullable type using the ? syntax:
int? nullableNumber = 20;
nullableNumber = null;Check if a nullable type has a value using HasValue:
if (nullableNumber.HasValue)
{
Console.WriteLine("Value is: " + nullableNumber.Value);
}
else
{
Console.WriteLine("No value");
}Use the null-coalescing operator ?? to provide a default value:
int definiteNumber = nullableNumber ?? 0;Try it yourself
using System;
class Program
{
// Implement the ProcessNullableAge method here
static void Main(string[] args)
{
string input = Console.ReadLine();
int? age = null;
if (input != "null")
{
age = int.Parse(input);
}
int result = ProcessNullableAge(age);
Console.WriteLine("Returned value: " + result);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsDeclaring and Initializing 2DAccessing 2D Array ElementsNested Loops with 2D ArraysJagged ArraysCommon Matrix OperationsRecap - Multi-dimensional4Flow Control Techniques
Early ReturnsGuard ClausesJump Statements (goto)Break and ContinueFlatten Nested Conditionals7Logical Operators Advanced
Short-Circuit EvaluationConditional Logical OperatorsOperator PrecedenceRecap - Advanced Operators2Advanced Decision Making
Multiple ConditionsComplex Boolean LogicIf vs. Switch ComparisonNested Switch StatementsRecap - Advanced Decisions5Exception Handling
Try-Catch BasicsException TypesMultiple Catch BlocksWorking with FilesFinally BlockUsing vs. Try-FinallyCustom ExceptionsRecap - Error Handling3Loop Enhancements
Loop PerformanceIterating ComplexEach Loop TypeRefactoring LoopsRecap - Optimized Loops6Null Handling
Null Reference BasicsNullable Value TypesNull Checking PatternsDefensive ProgrammingRecap - Null Safety