C# Null-Coalescing Operators Example – Simple Explanation with Code
Ever been scared of null
values in C#? Don’t worry, you’re not alone! 😅 Null values can be tricky, but that’s where Null-Coalescing Operators (??
and ??=
) come to the rescue. These operators help you handle null
values without writing long if-else
statements. Pretty cool, right?
??
Operator (Null-Coalescing)
- It checks if a value is
null
. - If it’s
null
, it returns a default value. - If it’s not null, it returns the original value.
Let’s see a C# Null-Coalescing Operators example in action:
using System;
class Program
{
static void Main()
{
string name = null;
string displayName = name ?? "Guest";
Console.WriteLine("Hello, " + displayName);
}
}
🖥 Output:
Hello, Guest
How It Works 🔍
name
isnull
.- The
??
operator checks ifname
has a value. If not, it assigns"Guest"
todisplayName
. - Instead of crashing, the program safely prints
"Hello, Guest"
.
See? No more worrying about null
values breaking your code! 😃
Real-World Scenario 🛒
Imagine you’re building an e-commerce app. A customer might not set a username, so you want to display "Anonymous"
instead. Here’s how C# Null-Coalescing Operators example can help:
using System;
class Customer
{
public string Username;
}
class Program
{
static void Main()
{
Customer user = new Customer();
string displayName = user.Username ?? "Anonymous";
Console.WriteLine("Welcome, " + displayName);
}
}
🖥 Output:
Welcome, Anonymous
Now, even if the username is null
, your app won’t crash!
The ??= Operator 🛠
C# also has the ??=
operator. It assigns a value only if the variable is null.
using System;
class Program
{
static void Main()
{
string userName = null;
userName ??= "DefaultUser";
Console.WriteLine("User: " + userName);
}
}
🖥 Output:
User: DefaultUser
Here, ??=
checks userName
. Since it’s null
, it assigns "DefaultUser"
. Simple and clean! 😃
Conclusion 🎯
The C# Null-Coalescing Operators example shows how you can handle null
values effortlessly. Instead of writing long if-else
conditions, just use ??
or ??=
and keep your code neat and readable. Try using them in your own projects—you’ll love the simplicity! 🚀
Next What? 🤔
👉 Up next, we’ll talk about Null-Conditional Operator – a super handy trick to handle null values without crashes!
Stay tuned! 😃