DEV Community

Juarez Júnior for Develop4Us

Posted on • Edited on

2

C# Tip: Simplified Nullable Types

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"}");
    }
}
Enter fullscreen mode Exit fullscreen mode

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

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (2)

Collapse
 
therealbadri profile image
Mahmood Elbadri

i noticed it today really helpful

Collapse
 
jangelodev profile image
João Angelo

Hi Juarez Júnior,
Top, thanks for sharing.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more