2

An unconstrained type parameter can be a nullable reference, non-nullable reference, value type or nullable value type.

Is it possible to roundtrip a parameter through object[?] ?

The following simplified code demonstrates the problem:

public static void Foo<U>(U unconstrainedParameter)
{
    object? nullableObject = unconstrainedParameter; 
    U assignBack = (U)nullableObject; // [CS8600] Converting null literal or possible null value to non-nullable type.
}

If we change nullableObject to type object then I get the error even at the assignment.

Is there some "trick" to do this roundtrip conversion without the need to suppress the warning (by using a nullable object and then ! when converting back)

Voo
  • 29,040
  • 11
  • 82
  • 156
  • check [this](https://stackoverflow.com/a/55492438/8588952) out – Mahdi Jul 27 '22 at 13:43
  • @Madhi Well yeah I know how to suppress nullability warnings (you can simply do `U assignBack = (U)nullableObject!` too. – Voo Jul 27 '22 at 13:47
  • No, there's no trick. What you're effectively asking for is a way to declare an `object` that's nullable or not depending on what the declared type of `U`'s value actually is, but that's beyond the ability of nullable annotations. Since `U` *might* be nullable, suppressing warnings here is the way to go (assuming you don't want to constrain the parameter, of course). – Jeroen Mostert Jul 27 '22 at 15:39

1 Answers1

0

The problem here is that U can be both null and not null. Given that the goal is to catch errors C# does the following:

  • when reading U it is assumed that the value can be null
  • when writing to U it is assumed that U could be non-nullable

Hence there is no possible workaround, since the casts can lead to errors in the general case. We just have additional information in the given scenario where we know this cannot happen.

Voo
  • 29,040
  • 11
  • 82
  • 156