Skip to content

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • Asp.Net Core
  • C#
  • SQL
  • JavaScript
  • CSS
  • About
  • ErcanOPAK.com
  • No Access
  • Privacy Policy
C#

C#: Use Null-Coalescing Operator for Null Safety

- 05.07.26 - ErcanOPAK

🛡️ Null Safety Made Easy

Null checks are verbose. Null-coalescing operators handle null elegantly. Provide defaults, chain checks, safe navigation.

❌ Verbose Null Checks

string name;
if (user != null && user.Name != null)
    name = user.Name;
else
    name = "Unknown";

✅ Null-Coalescing

string name = user?.Name ?? "Unknown";

📝 Null Operators

// Null-coalescing (??)
string name = user?.Name ?? "Unknown";
int age = user?.Age ?? 0;
double price = product?.Price ?? 0.0;

// Null-coalescing assignment (??=)
string name;
name ??= "Default Name"; // Only if null

// Null-conditional (?.)
string firstName = user?.Name?.FirstName; // Chain safely
int? orderCount = user?.Orders?.Count();
string street = user?.Address?.Street ?? "No address";

// Combining operators
string fullName = user?.FirstName?.ToUpper() ?? "Unknown";
string email = user?.Email?.Trim() ?? "No email";

// With nullable types
int? nullableAge = null;
int age = nullableAge ?? 25; // 25 if null

// With reference types
User? user = GetUser();
string name = user?.Name ?? "Guest";

// With Dictionaries
string value = dict?.GetValueOrDefault("key") ?? "default";

// With LINQ
var firstItem = list?.FirstOrDefault() ?? new Item();

🎯 Practical Examples

// Configuration
string apiKey = config["ApiKey"] ?? throw new Exception("ApiKey missing");
int timeout = int.Parse(config["Timeout"] ?? "30");

// Database operations
var user = await db.Users.FindAsync(id);
string displayName = user?.FullName ?? user?.Username ?? "Unknown User";

// API responses
var response = await httpClient.GetFromJsonAsync("...");
string token = response?.Data?.Token ?? "No token";

// Mapping
var dto = new UserDto
{
    Id = entity?.Id ?? 0,
    Name = entity?.Name ?? "Unknown",
    Email = entity?.Email?.ToLowerInvariant() ?? "no-email",
    CreatedAt = entity?.CreatedAt ?? DateTime.UtcNow
};

// Validation
string input = GetInput();
string sanitized = input?.Trim() ?? "";

// Event handling
string message = GetMessage() ?? "No message available";

// With arrays
string first = array?.FirstOrDefault() ?? "Empty";

// Complex chains
string result = data?.Items?.FirstOrDefault()?.Value?.ToString() ?? "No value";

✅ Benefits

  • Cleaner and more concise code
  • No null reference exceptions
  • Safe navigation through chains
  • Default values for nulls
  • Improved readability

“Null-coalescing operators handle null elegantly. No more verbose checks. Essential for modern C#.”

— Senior Developer

Related posts:

Default Values for Data Types in C#

C#: Use ObjectPool for Reusing Expensive Objects

C#: Use Interfaces to Define Contracts

Post Views: 5

Post navigation

C#: Use String Interpolation for Clean Formatting
Visual Studio: Use Refactoring Tools to Improve Code Quality

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

July 2026
M T W T F S S
 12345
6789101112
13141516171819
20212223242526
2728293031  
« Jun    

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (960)
  • How to add default value for Entity Framework migrations for DateTime and Bool (898)
  • How to make theater mode the default for Youtube (857)
  • Get the First and Last Word from a String or Sentence in SQL (840)
  • How to select distinct rows in a datatable in C# (814)
  • How to enable, disable and check if Service Broker is enabled on a database in SQL Server (597)
  • Add Constraint to SQL Table to ensure email contains @ (582)
  • Average of all values in a column that are not zero in SQL (545)
  • How to use Map Mode for Vertical Scroll Mode in Visual Studio (512)
  • Find numbers with more than two decimal places in SQL (460)

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes
  • Ajax: Use Axios for HTTP Requests
  • JavaScript: Understand Hoisting
  • HTML: Use Web Storage for Client-Side Data
  • CSS: Use Filter Effects for Visual Magic
  • Windows 11: Unlock God Mode for All Settings

Most Viewed Posts

  • Get the User Name and Domain Name from an Email Address in SQL (960)
  • How to add default value for Entity Framework migrations for DateTime and Bool (898)
  • How to make theater mode the default for Youtube (857)
  • Get the First and Last Word from a String or Sentence in SQL (840)
  • How to select distinct rows in a datatable in C# (814)

Recent Posts

  • C#: Use Using Statements for Resource Management
  • C#: Use Lambda Expressions for Concise Code
  • SQL: Use GROUP BY for Data Aggregation
  • .NET Core: Master Routing for Clean URLs
  • Git: Use Reset to Undo Local Changes

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com