Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • ⚡💰 Upgrade Your Account & Get Premium Benefits! 💰⚡

  • 📢 Contact if any issue or question

    Need help or have a question? Feel free to contact us on Telegram!

    📩 Contact on Telegram
  • 🚀 HOW TO EARN CREDITS, LOCK THREADS & HIDE THREADS! 🚀

Dometrain - From Zero to Hero Working with Null in C# 2025

Astaroth

Moderator
Moderator
Joined
Oct 13, 2023
Messages
1,568
Reaction score
756
Credits
1,887
Screenshot-from-2025-10-03-22-20-32.png

​

Learn how to properly use null in C# in a modern way and write better, robust code​


Null is often called the billion-dollar mistake, and for good reason. It can be very problematic. The idea of something having a nothing value sounds dangerous in software engineering. Over the years, C# has introduced features such as Nullable Reference Types to help developers write better, more robust, and safe code, but many people still don't know how to use it properly. In this course, Ed Charbeneau will start with the basics and teach you everything there is to know about null, from how to use it, from when not to use and how to take an existing full stack application that isn't using it properly and re-engineer it to make full use of the feature.


You must reply in thread to view hidden text or upgrade your account to always see hidden content.

​
 
Thanks a bunch.

Null in C# 2025: The Modern Way (With a Twist)

Ah, so you want to *really understand null in C#—not just the surface-level #nullable enable dance, but the dark art* of making it work for you instead of against you. Let’s cut through the fluff and get into the null-aware mindset.

---

**1. Nullable Reference Types (NRTs): The Basics (But Not *Really*)

First, the official way (because sometimes you *have* to play by the rules):

C#:
#nullable enable

public class Person
{
 public string? Name { get; set; } // Nullable reference type
 public DateTime? BirthDate { get; set; } // Also nullable
}

var person = new Person();
person.Name = null; // Compiler warns: "Cannot assign null to non-nullable reference type"
person.Name = "Alice"; // All good

But here’s the real question: Why does this even exist? Because null is a *lie. It’s not "nothing"—it’s a missing value, and treating it like a value leads to pain. NRTs force you to admit that some things might* be missing.

---

**2. When to Use Null (And When to *Not*)

**
  • Use null when:
    - You *explicitly* need to represent "no value" (e.g., string? for optional strings).
    - You’re working with APIs/database fields that *can* legitimately be empty.
    - You’re doing optional chaining (person?.Name?.Length) to avoid NullReferenceException.
  • Avoid null when:
    - You can use default values (string.Empty instead of null for strings).
    - You can enforce non-nullability (e.g., Required attribute in DTOs).
    - You’re dealing with collections—use IReadOnlyList<T> or IEnumerable<T> with empty collections instead of null.

---

**3. The *Real* Problem: Nullable Wrappers (Nullable<T>)

C#:
int? age = null; // Nullable<int> is just a wrapper around int + a flag
Console.WriteLine(age.HasValue); // true (if not null)
Console.WriteLine(age.Value); // Throws if null (use age.GetValueOrDefault() instead)

Problem: Nullable<T> is just syntactic sugar for a struct that *might hold a value. It’s not safe—it’s just explicit*.

Better approach:
C#:
public record NonNullablePerson(string Name, DateTime BirthDate); // No nulls allowed
var person = new NonNullablePerson("Bob", DateTime.Now); // Compiler enforces non-null

---

**4. The *Modern* Way: Pattern Matching & Null-Conditional Operators

Instead of:
C#:
if (person != null && person.Name != null)
{
 Console.WriteLine(person.Name.Length);
}

Do this:
C#:
if (person is { Name: not null })
{
 Console.WriteLine(person.Name.Length); // Clean, no nested null checks
}

Or with null-coalescing:
C#:
string name = person?.Name ?? "Unknown"; // "Unknown" if person or Name is null

---

**5. The *Dark Side*: When NRTs Fail You

NRTs are not magic. They won’t save you from:
  • Legacy code where null is everywhere.
  • Third-party libraries that ignore NRTs.
  • Your own brain when you forget to mark a field as nullable.

Solution? Refactor aggressively.
  • Replace List<T> with IReadOnlyList<T> and return empty lists instead of null.
  • Use Maybe<T> (from libraries like LanguageExt) for explicit "maybe" semantics.
  • Delete null checks where possible—use is patterns or ??.

---

**6. The *Final* Truth: Null is a Symptom, Not the Disease

The real issue isn’t null—it’s bad design.
  • If a method *can* return null, ask: "Should it?"
  • If a property *can* be null, ask: "What does that mean?"
  • If you’re using null as a control flow hack, you’re doing it wrong.

**Example of *good* null handling:**
C#:
public class UserService
{
 public User GetUserById(int id) => _dbContext.Users.FirstOrDefault(u => u.Id == id);
 // Returns null if not found (explicit, but documented)
}

public class UserController
{
 private readonly UserService _userService;

 public IActionResult GetUser(int id)
 {
 var user = _userService.GetUserById(id);
 return user is not null
 ? Ok(user)
 : NotFound(); // Better than throwing or returning null
 }
}

---

**7. The *Bonus* Round: Null in Async Code

C#:
public async Task<User?> GetUserAsync(int id)
{
 return await _dbContext.Users
 .FirstOrDefaultAsync(u => u.Id == id);
 // Returns Task<User?> (nullable reference)
}

var user = await GetUserAsync(1);
if (user is not null)
{
 Console.WriteLine(user.Name);
}

Key takeaway: Task<T> is already nullable-friendly. Just be consistent.

---

**Final Verdict: Null is a Tool, Not a Crutch

  • Use NRTs to make null *explicit*.
  • Avoid null where possible—use defaults, Maybe<T>, or IReadOnlyCollection<T>.
  • Refactor old code—don’t just slap #nullable enable on it.
  • Document your null cases—if a method returns null, *say why*.

And if all else fails? Write your own Maybe<T> monad. Because in the end, null is just a failed abstraction—and abstractions are what make code *good*.

---
Now go forth and write null-free code. 🚀
 
Back
Top