10.Nullable Reference Types & Null Handling - aniketmulmule/web_Project GitHub Wiki
Hereβs a deep dive into Nullable Reference Types (NRT) & Null Handling in C#, especially important for experienced .NET developers (8+ years) preparing for interviews, with practical code samples, real-world use, and interview insights.
Introduced in C# 8.0, NRT helps avoid
NullReferenceException
, the most common runtime error in .NET.
Mark reference types as nullable or non-nullable explicitly:
string name = null; // β οΈ Warning: possible null assignment
string? name = null; // β
Allowed, explicitly nullable
Add this to .csproj
:
<Nullable>enable</Nullable>
Or use:
#nullable enable
Type | Meaning |
---|---|
string | Must never be null (compiler will warn if it might be) |
string? | Nullable reference type β must be checked before use |
Would you like this in:
-
π PDF format with checklists?
-
β Practice quiz or real-world refactor task?
-
π§ Nullable adoption strategy for existing codebase?
Let me know β I can generate it right away.
Hereβs a **deep dive into Nullable Reference Types (NRT) & Null Handling in C#**, especially important for **experienced .NET developers (8+ years)** preparing for **interviews**, with practical code samples, real-world use, and interview insights.Introduced in C# 8.0, NRT helps avoid
NullReferenceException
, the most common runtime error in .NET.
Mark reference types as nullable or non-nullable explicitly:
string name = null; // β οΈ Warning: possible null assignment
string? name = null; // β
Allowed, explicitly nullable
Add this to .csproj
:
<Nullable>enable</Nullable>
Or use:
#nullable enable
Type | Meaning |
---|---|
string |
Must never be null (compiler will warn if it might be) |
string? |
Nullable reference type β must be checked before use |
string? name = GetUserName();
if (name != null)
Console.WriteLine(name.Length); // β
safe access
NRT uses static code analysis to issue warnings, not runtime errors.
public string? GetUserName() => null;
var name = GetUserName();
Console.WriteLine(name.Length); // β οΈ warning: possible dereference of null
Feature | Nullable Value Type | Nullable Reference Type |
---|---|---|
Example |
int? , bool?
|
string? , User?
|
Null support | Yes | Yes (with C# 8+) |
Checked by compiler | No | Yes |
Use case | Optional primitives | Avoid null-related bugs |
Use !
to suppress compiler warnings when you're sure the value isn't null.
string? name = GetUserName();
Console.WriteLine(name!.Length); // suppress warning
!
defeats the purpose of NRT.
- β
Use
string?
only when null is expected - β
Validate parameters with
[NotNull]
,[DisallowNull]
, or manualArgumentNullException
- β Apply defensive programming for external inputs (APIs, user input, DB)
- β Avoid overusing
!
null-forgiving operator
Used especially in library design and validation:
Attribute | Use |
---|---|
[NotNull] |
Guarantees output is not null |
[MaybeNull] |
Output might be null |
[DisallowNull] |
Input must not be null |
[AllowNull] |
Input can be null even if the type is non-nullable |
public void SetName([DisallowNull] string name) { ... }
Scenario | Benefit of NRT |
---|---|
API Controllers | Ensure inputs/outputs aren't null |
Entity Models | Avoid null mapping errors |
UI Form Binding | Ensure required fields |
Service Layer | Clear intent of nullable return values |
Question | What You Should Explain |
---|---|
What are nullable reference types? | Feature from C# 8 to reduce null reference bugs |
How are they different from nullable value types? | Nullable value types have been around since .NET 2.0 |
How does the compiler enforce NRT? | Static analysis (compile-time warnings) |
When would you still allow a null? | Optional values, deferred initialization |
Have you used nullable annotations in APIs? | Use [MaybeNull] , [NotNull] , [AllowNull] in public contracts |
public class UserDto
{
public string FirstName { get; set; } // Non-null
public string? MiddleName { get; set; } // Optional
}
[HttpPost]
public IActionResult CreateUser(UserDto user)
{
// No need for null check on FirstName
}
In mixed codebases:
- NRT analysis won't apply to pre-C#8 projects unless enabled.
- You may need to annotate third-party library usage manually.
Resource | Link |
---|---|
Microsoft Docs - Nullable Ref Types | [Learn C# Nullable](https://learn.microsoft.com/en-us/dotnet/csharp/nullable-references) |
C# Language Reference | [Nullable Types](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types) |
Pluralsight β C# Null Safety | [Pluralsight Course](https://www.pluralsight.com/courses/csharp-8-null-safety) |
SharpLab β Live Compiler Playground | https://sharplab.io/ |
Feature | Purpose |
---|---|
string vs string?
|
Enforce null safety |
! null-forgiving |
Suppress compiler warning |
Attributes | Help enforce null intent across boundaries |
.csproj <Nullable>enable</Nullable>
|
Enables NRT checks project-wide |
Main Benefit | Prevents runtime NullReferenceException
|
Would you like this in:
- π PDF format with checklists?
- β Practice quiz or real-world refactor task?
- π§ Nullable adoption strategy for existing codebase?
Let me know β I can generate it right away.