🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)
🔧 AI Nachrichten Major AI platforms go down in unprecedented simultaneous outage(03.09.2026 um 17:34 Uhr)
🔧 AI Nachrichten ChatGPT, Claude, and Grok Down? Users Report Widespread Outages(03.09.2026 um 19:14 Uhr)
🔧 AI Nachrichten OpenAI Launches GPT-6 Astra, Says We May Have Entered the AGI Era(03.09.2026 um 22:08 Uhr)
🔧 AI Nachrichten Claude Comes to CarPlay as Fifth Major AI Chatbot App(05.09.2026 um 05:31 Uhr)
🔧 AI Nachrichten OpenAI’s GPT-6 Astra Is AGI, Says NVIDIA CEO Jensen Huang(07.09.2026 um 06:31 Uhr)
🔧 AI Nachrichten Blame AI companies for Mac mini and Mac Studio shortage(31.08.2026 um 10:32 Uhr)

🔧 Programmierung 🕛 kürzlich 4 Min Lesezeit
0

Understanding Nullable Reference Types in C#

↗ Quelle (dev.to)
🗣️ Stimme:
📑 Inhaltsübersicht




Introduction



Nullable reference types in C# allow developers to explicitly specify whether a reference type can or cannot be null. This feature significantly reduces null reference exceptions, which are a common source of bugs. In this article, we’ll explore how to handle nullable reference types effectively and ensure safe code practices with a practical example.









Practical Example: User Registration



Consider a class UserRegistrationEventArgs, which represents event arguments passed during user registration.









1. Initial Implementation: The Problem



Here’s a basic implementation without handling nullable reference types:




CODE
public class UserRegistrationEventArgs : EventArgs
{
public string UserName { get; init; }
public string Email { get; init; }
}






If nullable reference types are enabled, the compiler generates warnings because:





  1. UserName and Email are non-nullable properties.

  2. There is no guarantee that these properties will be initialized.









2. Solutions






Solution 1: Use a Constructor


Add a constructor to ensure properties are initialized:




CODE
public class UserRegistrationEventArgs : EventArgs
{
public string UserName { get; }
public string Email { get; }

public UserRegistrationEventArgs(string userName, string email)
{
UserName = userName ?? throw new ArgumentNullException(nameof(userName));
Email = email ?? throw new ArgumentNullException(nameof(email));
}
}






This eliminates warnings and ensures UserName and Email are initialized when an instance is created. Example usage:




CODE
var args = new UserRegistrationEventArgs("JohnDoe", "[email protected]");
Console.WriteLine($"User Registered: {args.UserName}, {args.Email}");












Solution 2: Mark Properties as Nullable


Alternatively, mark the properties as nullable if null is acceptable:




CODE
public class UserRegistrationEventArgs : EventArgs
{
public string? UserName { get; init; }
public string? Email { get; init; }
}






In this case, you must check for null values when accessing the properties:




CODE
var args = new UserRegistrationEventArgs { UserName = null, Email = "[email protected]" };

if (args.UserName == null)
{
Console.WriteLine("UserName is not set.");
}
else
{
Console.WriteLine($"User Registered: {args.UserName}, {args.Email}");
}












3. Handling Nullable Parameters in Methods



Let’s see how this applies to a UserService that processes user registration:




CODE
public class UserService
{
public void RegisterUser(UserRegistrationEventArgs args)
{
if (args == null) throw new ArgumentNullException(nameof(args));

if (string.IsNullOrEmpty(args.UserName))
{
Console.WriteLine("Invalid registration: UserName is required.");
}
else
{
Console.WriteLine($"User Registered: {args.UserName}, {args.Email ?? "No Email Provided"}");
}
}
}






Usage:




CODE
var userService = new UserService();

// Case 1: Valid registration
var validArgs = new UserRegistrationEventArgs { UserName = "JohnDoe", Email = "[email protected]" };
userService.RegisterUser(validArgs);

// Case 2: Invalid registration
var invalidArgs = new UserRegistrationEventArgs { UserName = null, Email = "[email protected]" };
userService.RegisterUser(invalidArgs);












4. Flexible Method Parameters



If your method can handle nullable references, update the signature:




CODE
public void RegisterUser(string? userName, string? email)
{
if (string.IsNullOrEmpty(userName))
{
Console.WriteLine("Invalid registration: UserName is required.");
}
else
{
Console.WriteLine($"User Registered: {userName}, {email ?? "No Email Provided"}");
}
}






Usage:




CODE
var userService = new UserService();
userService.RegisterUser("JohnDoe", null); // Valid
userService.RegisterUser(null, "[email protected]"); // Invalid












5. Best Practices for Nullable Reference Types





  1. Use Constructors for Mandatory Properties: This ensures required properties are initialized during object creation.


  2. Mark Optional Properties as Nullable: Explicitly mark properties that can be null with ?.


  3. Guard Against Null: Use null checks or operators like ?? to handle null values safely.


  4. Adopt Gradual Migration: Use #nullable directives to enable or disable nullable reference types in specific parts of the codebase when refactoring legacy projects.









Full Example: User Registration System



Here’s the complete code:




CODE
using System;

#nullable enable

public class UserRegistrationEventArgs : EventArgs
{
public string UserName { get; init; }
public string Email { get; init; }

public UserRegistrationEventArgs(string userName, string email)
{
UserName = userName ?? throw new ArgumentNullException(nameof(userName));
Email = email ?? throw new ArgumentNullException(nameof(email));
}
}

public class UserService
{
public void RegisterUser(UserRegistrationEventArgs args)
{
if (args == null) throw new ArgumentNullException(nameof(args));

if (string.IsNullOrEmpty(args.UserName))
{
Console.WriteLine("Invalid registration: UserName is required.");
}
else
{
Console.WriteLine($"User Registered: {args.UserName}, {args.Email ?? "No Email Provided"}");
}
}
}

class Program
{
static void Main()
{
var userService = new UserService();

// Valid registration
var validArgs = new UserRegistrationEventArgs("JohnDoe", "[email protected]");
userService.RegisterUser(validArgs);

// Invalid registration
var invalidArgs = new UserRegistrationEventArgs(null!, "[email protected]");
userService.RegisterUser(invalidArgs);
}
}












Conclusion



Nullable reference types are a powerful feature that improves code safety by reducing null reference exceptions. By explicitly specifying nullability and adhering to best practices, you can write cleaner, more robust code. Whether you’re using constructors or nullable properties, always ensure clarity and consistency in how your classes and methods handle null values.

Vollständiger Original-Bericht
Ausführliche Details, Code-Beispiele & Hersteller-Stellungnahme auf dev.to.
↗ Original-Artikel auf dev.to lesen
Wie bewertest du diesen Beitrag?
1 Klick Feedback
Teilen mit Netzwerk & Team:

Community-Analysen & Experten-Meinungen 0

Verfasse deine eigene Analyse, teile Workarounds oder diskutiere diesen Vorfall im Blog.
Noch keine Community-Analyse verfasst. Markiere einen Textabschnitt oder klicke oben auf Eigene Analyse verfassen“!
Community Pulse: Relevanz-Einschätzung
1 Klick Experten-Votum
🔴 Akute Relevanz 0%
🟡 In Evaluierung 0%
🟢 Keine Auswirkung 0%
Spannende Innovation 0%
Verwandte Story-Cluster & Quellen (Vektor-KI)
Port 8095 Engine
3 Quellen
GPT-6 Astra Release Today? OpenAI’s Next Major AI Model Is Almost Here
1 Quelle
Apple accuses OpenAI of destroying evidence as trade-secrets fight intensifies
1 Quelle
Major AI platforms go down in unprecedented simultaneous outage
Ähnliche Beiträge
🔍 Verwandte News

Auch interessante Nachrichten Understanding Nullable Reference Types in C#

Thematisch verwandte Begriffe: Understanding, Nullable, Reference, Types · 6 Treffer

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...

Laden...

Beiträge werden geladen ...

Laden...

Videos werden geladen ...