Skip to main content
C# Fundamentals for Beginners to Advanced
CHAPTER 30 Beginner

Modern C# Features and Best Practices

Updated: May 17, 2026
5 min read

# CHAPTER 30

Modern C# Features and Best Practices

1. Introduction

C# was released in 2000. Over two decades later, it is on version C# 12 (and beyond), continuously evolving to become more concise, functional, and safe. In this final chapter, we will explore the modern features that have transformed the language, and review the universal best practices for writing Clean Code.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use Top-Level Statements (C# 9).
  • Understand and use record types for immutable data.
  • Use advanced Pattern Matching.
  • Understand Nullable Reference Types to prevent crashes.
  • Apply Clean Code principles.

3. Top-Level Statements (C# 9.0)

Historically, every C# console application required a massive amount of boilerplate code:
csharp
123456789101112
// The Old Way
using System;
namespace MyApp
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
        }
    }
}

In modern C#, you can delete all of that. The compiler generates the namespace, class, and Main method for you automatically.

csharp
12
// The Modern Way (Top-Level Statements)
Console.WriteLine("Hello World!");

4. Records (C# 9.0)

When creating data models that shouldn't change after they are created (Immutable Data), developers used to write massive classes with private set properties.

A record is a special class designed specifically for immutable data. It provides value-based equality out of the box (if two records have the same data, they are considered equal, unlike standard classes).

csharp
123456789
// Defines an entire immutable class in ONE line!
public record Employee(int Id, string Name);

// Usage
var emp1 = new Employee(1, "Alice");
var emp2 = new Employee(1, "Alice");

// In standard classes, this would be false. With records, it is true!
Console.WriteLine(emp1 == emp2); 

5. Advanced Pattern Matching (C# 8 & 9)

We saw basic switch expressions in Chapter 7. Modern pattern matching allows for highly complex logic evaluations instantly.
csharp
12345678910
int temp = 25;

// Property Pattern Matching
string weather = temp switch
{
    < 0 => "Freezing",
    >= 0 and < 15 => "Cold",
    >= 15 and <= 25 => "Perfect",
    > 25 => "Hot"
};

6. Nullable Reference Types (C# 8.0)

The "Billion Dollar Mistake" in programming is the NullReferenceException. Historically, any string or object could silently hold a null value, crashing the program when accessed.

Modern C# forces you to explicitly declare if a variable is allowed to be null using the ? operator.

csharp
123456789
// string name = null; // WARNING: Non-nullable string cannot be null!

string? optionalName = null; // OK! The ? marks it as explicitly nullable

// The compiler now FORCES you to check for null before using it:
if (optionalName != null)
{
    Console.WriteLine(optionalName.Length);
}

7. Clean Code Best Practices

  1. 1. Meaningful Names: Avoid variables like int d;. Use int daysUntilExpiry;.
  1. 2. Single Responsibility Principle: A class or method should have only one reason to change. If your User class sends emails, validates passwords, and saves to the database, it is doing too much.
  1. 3. Don't Repeat Yourself (DRY): If you copy and paste a block of code 3 times, extract it into a Method.
  1. 4. Fail Fast: Validate data at the very beginning of your method and throw an exception immediately if it is invalid, rather than letting the code run and fail deep inside complex logic.
  1. 5. Comment the 'Why', not the 'What':
*Bad:* count++; // Increments count (I can read the code, I know what it does). *Good:* count++; // Adjusting for the zero-index offset in the legacy API.

8. Common Mistakes

  • Ignoring Compiler Warnings: Modern C# uses Nullable Reference Types to generate warnings, not errors. Many developers ignore them. If you treat warnings as errors, your applications will almost never crash in production.

9. Conclusion of the Course

You have completed the C# Fundamentals course! You have journeyed from basic variables to object-oriented architecture, asynchronous tasks, and database connections. You are now equipped to build enterprise-grade software. The next step is building projects—try building a REST API using ASP.NET Core, or a desktop app using WPF. Keep coding!

10. MCQs with Answers

Question 1

What C# 9 feature eliminates the need to write class Program { static void Main() }?

Question 2

Which keyword is used to create a lightweight, immutable class designed for holding data?

Q3. How do record types compare equality? a) By memory address (Reference equality) b) By the actual data they contain (Value equality) Answer: b) By the actual data they contain (Value equality)
Question 4

What feature allows you to replace complex if-else chains with concise logic mapping (e.g., < 0 => "Freezing")?

Question 5

What symbol is used to explicitly mark a Reference Type (like a string) as nullable?

# Answer: b) ? (e.g., string?)
Question 6

What happens if you try to access a property on a Nullable Reference Type without checking for null first?

Question 7

What does the DRY principle stand for?

Question 8

What does the Single Responsibility Principle dictate?

Q9. Which is a better comment? a) x = 5; // Set x to 5 b) x = 5; // Default max retry limit for API timeout Answer: b) x = 5; // Default max retry limit for API timeout

Q10. Is C# a stagnant language, or does it receive constant updates? a) It hasn't changed since 2005 b) It is aggressively updated by Microsoft, with new syntax and features added annually Answer: b) It is aggressively updated by Microsoft, with new syntax and features added annually

11. Interview Questions

  • Q: What is a record in C#, and when would you use it instead of a class?
  • Q: Explain Nullable Reference Types and how they help prevent the "Billion Dollar Mistake".

12. Final Thoughts

Thank you for learning C#. By combining the syntax, OOP architecture, and modern features discussed in this course, you are well on your way to becoming a professional .NET Software Engineer.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·