Modern C# Features and Best Practices
# 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
recordtypes 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:In modern C#, you can delete all of that. The compiler generates the namespace, class, and Main method for you automatically.
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 withprivate 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).
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.6. Nullable Reference Types (C# 8.0)
The "Billion Dollar Mistake" in programming is theNullReferenceException.
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.
7. Clean Code Best Practices
-
1.
Meaningful Names: Avoid variables like
int d;. Useint daysUntilExpiry;.
-
2.
Single Responsibility Principle: A class or method should have only one reason to change. If your
Userclass sends emails, validates passwords, and saves to the database, it is doing too much.
- 3. Don't Repeat Yourself (DRY): If you copy and paste a block of code 3 times, extract it into a Method.
-
4.
Fail Fast: Validate data at the very beginning of your method and
throwan exception immediately if it is invalid, rather than letting the code run and fail deep inside complex logic.
- 5. Comment the 'Why', not the 'What':
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
What C# 9 feature eliminates the need to write class Program { static void Main() }?
Which keyword is used to create a lightweight, immutable class designed for holding data?
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)
What feature allows you to replace complex if-else chains with concise logic mapping (e.g., < 0 => "Freezing")?
What symbol is used to explicitly mark a Reference Type (like a string) as nullable?
string?)
What happens if you try to access a property on a Nullable Reference Type without checking for null first?
What does the DRY principle stand for?
What does the Single Responsibility Principle dictate?
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
recordin C#, and when would you use it instead of aclass?
- Q: Explain Nullable Reference Types and how they help prevent the "Billion Dollar Mistake".