C# Uri? vs. Nullable<Uri>

Viewed 115

I've always known in C# that you can represent nullable types in multiple ways, with the difference often being described as "syntactic sugar". For example, the following...

// Case 1
int? nullableIntegerVar01;
// Case #2 - 
System.Nullable<int> nullableIntegerVar02;
// Case #3 - 
Uri? nullableUriVar01;
// Case #4 
System.Nullable<Uri> nullableUriVar02;

Oddly, case #4 above does not compile and throw the following error.

"Error CS0453 The type 'Uri' must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method 'Nullable'"

I understand the error, I do not understand the reasoning - I expected these two methods of defining nullable types to be interchangeable.

Further, the following does not work.

var testType = typeof(Uri);
var testNullableType = typeof(Nullable<>).MakeGenericType(testType);

Can anyone provide insight?

1 Answers

For value types, such as int or structs (that normally can never be null), x? is equivalent to Nullable<x> (syntactic sugar), and it creates a new type. For reference types such as Uri the ? only serves as an annotation, it doesn't create a new type (these can be null regardless of the presence of the ? marker).

Docs:

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-reference-types

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types

Related