Nullable vs. Nullable in C#
16 days ago
- #Nullable Types
- #C#
- #Programming
- The `T?` syntax in C# represents two different concepts for value types and reference types, leading to confusion.
- Nullable value types (`T?`) were introduced in C# 2.0 and are syntactic sugar for `Nullable<T>`, making `T?` and `T` distinct types.
- Nullable reference types (`T?`) were introduced in C# 8.0 and serve as a communication tool about null expectations, with `T?` and `T` being the same type at runtime.
- The overloading of `T?` causes issues, such as in the `SelectNotNull` method, where it fails to work seamlessly for both value and reference types.
- A workaround involves creating two overloaded methods with different type constraints (`where TR : class` and `where TR : struct`) to handle both scenarios.
- This solution, while functional, highlights the complexity and oddity of reusing `T?` for two distinct purposes in C#.