Nullable vs. Nullable in C#

https://news.ycombinator.com/rss Hits: 4
Summary

Nullable vs nullable in C# August 25, 2025 One of the most unfortunate parts of the nullability narrative in C# is the reuse of the T? syntax to denote two completely separate concepts for value types and reference types. This leads to some odd and confusing behaviour. As you may know, nullable value types is a much older concept than nullable reference types. Nullable value types were introduced in C# 2.0, whereas nullable reference types came in C# 8.0. And they’re not the same. Nullable isn’t nullable. For value types, T? is syntactic sugar for the wrapper type Nullable<T>. An expression like int? maybe = 5 compiles to int? maybe = new Nullable(5), wrapping the integer value in a nullable value. This means that T? and T are distinct types. Nullable reference types are a very different beast. For reference types, T? is a communication device. It says something about intentions. In essence it says “I expect nulls here”. Its counterpart T communicates the opposite: “there shouldn’t be nulls here”. But once the compiler has done its job of warning that you may be violating your own intentions, there is no difference. T? and T are the same type, and that type allows nulls. “So what?” you may ask. How is this a problem? I’m glad you asked! Let’s take a look at an example to illustrate the consequences of overloading T? to mean different things for value types and reference types. The Enumerable class contains many extension methods for types that implement the IEnumerable<T> interface. However, it does not contain a method that corresponds to List.choose in F#! Let’s try to fix that. List.choose is interesting in that it combines the effect of map and filter, or Select and Where in C#. It maps each element of a list to an optional value of some type, and then it filters based on that mapping, keeping only the genuine values as it were. In case that’s not entirely clear, my first naive attempt at writing such a method in C# should make it clearer. public static IEnumera...

First seen: 2025-08-29 11:32

Last seen: 2025-08-29 15:34