Question
I came across this line of C# code:
CopyFormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
What does the ?? operator mean in this context? Is it a kind of ternary operator?
I am also finding it difficult to search for because two question marks are hard to look up directly.
Short Answer
By the end of this page, you will understand what the ?? operator does in C#, why it is called the null-coalescing operator, and how it helps you provide a fallback value when something is null. You will also see how it compares to the ternary operator, how it is used in real codebases, and what common mistakes to avoid.
Concept
The ?? operator in C# is called the null-coalescing operator.
It is used to choose a fallback value when the expression on the left is null.
Core idea
result = leftValue ?? fallbackValue;
This means:
- If
leftValueis not null, use it. - If
leftValueis null, usefallbackValue.
So this code:
CopyFormsAuth = formsAuth ?? new FormsAuthenticationWrapper();
means:
- If
formsAuthalready has an object, assign that object toCopyFormsAuth. - Otherwise, create a new
FormsAuthenticationWrapperand assign that instead.
Why this matters
In real programs, values are often optional or missing:
- a method parameter may not be provided
- a configuration value may be absent
- a database field may be null
- an object may not have been created yet
The ?? operator lets you handle those cases clearly and compactly.
Equivalent longer form
Mental Model
Think of ?? as a backup choice operator.
Imagine you are trying to sit in your assigned chair:
- If your chair is available, sit there.
- If your chair is missing, use the spare chair.
That is exactly what ?? does:
chairToUse = assignedChair ?? spareChair;
Another way to think about it:
- left side = your first choice
- right side = your backup plan
If the first choice exists, use it. If not, use the backup.
Syntax and Examples
Basic syntax
value = possibleNullValue ?? fallbackValue;
Example 1: String fallback
string name = null;
string displayName = name ?? "Guest";
Console.WriteLine(displayName);
Output:
Guest
Because name is null, C# uses "Guest".
Example 2: Existing value is kept
string name = "Ava";
string displayName = name ?? "Guest";
Console.WriteLine(displayName);
Output:
Ava
Because name is not null, the fallback is ignored.
Example 3: Objects
User currentUser = ;
User userToDisplay = currentUser ?? User();
Step by Step Execution
Consider this code:
string inputName = null;
string finalName = inputName ?? "Guest";
Console.WriteLine(finalName);
Here is what happens step by step:
inputNameis created and set tonull.- C# evaluates
inputName ?? "Guest". - It checks the left side:
inputName. - Because
inputNameisnull, C# uses the right side:"Guest". finalNamebecomes"Guest".Console.WriteLine(finalName);printsGuest.
Now look at this version:
string inputName = "Mina";
string finalName = inputName ?? "Guest";
Console.WriteLine(finalName);
Step by step:
Real World Use Cases
Default values for optional data
string theme = savedTheme ?? "light";
If a user has not chosen a theme yet, the app uses "light".
Dependency fallback
_logger = logger ?? new ConsoleLogger();
If no logger is provided, use a default one.
Configuration values
string connectionString = configValue ?? "Server=localhost;Database=AppDb;";
Useful when configuration is missing in development.
API or database values
string city = customer.City ?? "Unknown";
If the database field is null, show a safe display value.
Constructor initialization
public ReportService(IFormatter formatter)
{
_formatter = formatter ?? new DefaultFormatter();
}
This pattern is common in dependency injection and testable code.
Real Codebase Usage
In real projects, developers use ?? to make null-handling shorter and easier to read.
Common patterns
1. Constructor defaults
public MyService(ICache cache)
{
_cache = cache ?? new MemoryCache();
}
This gives the class a working dependency even if none is passed in.
2. Guarding optional return values
var name = repository.GetDisplayName(userId) ?? "Anonymous";
This avoids extra if statements.
3. Safe model preparation
viewModel.Title = article.Title ?? "Untitled";
Useful when preparing data for UI output.
4. Chaining with null-aware code
string zip = customer?.Address?.ZipCode ?? "No ZIP";
This combines:
?.to safely access nested members??to provide a fallback if the result is null
Common Mistakes
Mistake 1: Thinking ?? checks for false or empty values
?? only checks for null.
It does not treat these as null:
false0""(empty string)
Example
string text = "";
string result = text ?? "default";
Console.WriteLine(result);
Output is an empty string, not default.
If you want to treat empty strings specially, use something like:
string result = string.IsNullOrEmpty(text) ? "default" : text;
Mistake 2: Confusing ?? with the ternary operator
Broken understanding:
// This is not what ?? means
value = condition ?? option1 : option2;
Comparisons
| Concept | Purpose | Example | Best when |
|---|---|---|---|
?? | Use a fallback if a value is null | name ?? "Guest" | You only care about null |
?: | Choose between two values based on a condition | age >= 18 ? "Adult" : "Minor" | You need true/false logic |
if/else | Full branching logic | if (x == null) ... | Logic is more complex or needs multiple steps |
??= | Assign only if current value is null |
Cheat Sheet
Quick syntax
value = possibleNull ?? fallback;
Meaning
- left side not null -> use left side
- left side null -> use right side
Example
string name = null;
string display = name ?? "Guest";
Equivalent code
string display = name != null ? name : "Guest";
Common uses
- default constructor arguments
- fallback strings
- optional configuration values
- object initialization
- nullable value types
Works with
- reference types
- nullable value types like
int?,bool?,DateTime?
Does not check
- empty string
"" 0
FAQ
What does ?? mean in C#?
It is the null-coalescing operator. It returns the left value if it is not null; otherwise, it returns the right value.
Is ?? the same as the ternary operator?
No. The ternary operator ?: works with any boolean condition. ?? is specifically for null fallback.
Does ?? work with empty strings?
No. An empty string is not null. Use string.IsNullOrEmpty() if you want to handle both.
Can I use ?? with integers in C#?
Yes, if the integer is nullable, such as int?. A plain int cannot be null.
What is ??= in C#?
It is the null-coalescing assignment operator. It assigns a value only if the variable is currently null.
Why is ?? useful in constructors?
It lets you provide a default dependency or value when an argument is null, keeping constructor code short and readable.
Mini Project
Description
Build a small C# console program that displays a user's nickname if one exists, or a default value if it does not. This demonstrates how the null-coalescing operator simplifies fallback logic in a practical program.
Goal
Create a program that safely handles missing values by using ?? to provide defaults.
Requirements
- Create a nullable or reference-type variable that may contain
null - Use the
??operator to provide a fallback value - Print the final result to the console
- Add a second example where the original value is not null
Keep learning
Related questions
AddTransient vs AddScoped vs AddSingleton in ASP.NET Core Dependency Injection
Learn the differences between AddTransient, AddScoped, and AddSingleton in ASP.NET Core DI with examples and practical usage.
C# Type Checking Explained: typeof vs GetType() vs is
Learn when to use typeof, GetType(), and is in C#. Understand exact type checks, inheritance, and safe type testing clearly.
C# Version Numbers Explained: C# vs .NET Framework and Why “C# 3.5” Is Incorrect
Learn the correct C# version numbers, how they map to .NET releases, and why terms like C# 3.5 are inaccurate and confusing.