Код: Выделить всё
using System.Diagnostics;
List xs = new() { "a", "b" };
// normally xs would be the result of a method call that returns List,
// but for some reason, we know it's List
// so we first do a sanity check
if (xs.Exists(x => x is null))
{
throw new UnreachableException("Something is broken, we expected no nulls");
}
// and we want to cast it. That doesn't work:
List ys = xs;
// that doesn't work either:
List zs = (List)(object)xs;
Код: Выделить всё
Nullability of reference types in value of type 'System.Collections.Generic.List' does not match target type 'System.Collections.Generic.List'

Под «это тоже не работает» я имею в виду, что больше не получаю указанную выше ошибку, но получаю:
Код: Выделить всё
Type cast is redundant

Обратите внимание:
Код: Выделить всё
List ys = (List)xs
Код: Выделить всё
List ys = xs;
Ни одно из этих решений не кажется удовлетворительным.
(Я использую .NET = 10.0.104 и пишу код на RIDER = JetBrains Rider 2026.1.0.1. Я использую .NET & RIDER на компьютере с Windows 11.)