Let’s talk about Simplified Nullable Types, introduced in C# 8, which allow you to declare variables and types that accept null more clearly and safely, helping to avoid null reference errors. See the example:
#nullable enable
public class Person
{
public string Name { get; set; }
public string? Nickname { get; set; } // Can accept null
}
public class Program
{
public static void Main()
{
Person person = new Person { Name = "John", Nickname = null };
Console.WriteLine($"Name: {person.Name}, Nickname: {person.Nickname ?? "None"}");
}
}
With Simplified Nullable Types, the C# 8 compiler can help identify variables that may contain null, enhancing code safety. When the feature is enabled, type variables and references are, by default, considered non-nullable, meaning you must explicitly declare when a variable can accept null using the ? operator. This significantly reduces null reference errors, as the compiler warns you when a null value is being assigned to a variable that does not accept it.
This feature is especially useful in large projects, where code safety and robustness are critical, allowing developers to handle null more explicitly and controlled.
Source code: GitHub
Top comments (2)
i noticed it today really helpful
Hi Juarez Júnior,
Top, thanks for sharing.