3

In C# what does where T : class? mean (note the question mark on the end of the class constraint)

For instance

public IList<T> DoThis<T>() where T : class?
kimsagro
  • 15,513
  • 17
  • 54
  • 69

3 Answers3

4

? attached to a type in C# (supported from version 8) means it is a nullable reference type. class? means that the calling code has to pass in a type parameter which is a class, and may be nullable.

For instance, DoThis<string?>(someNullableString) is valid. It may also be called with the non-nullable version, e.g. DoThis<string>(someNonNullableString).

eouw0o83hf
  • 9,438
  • 5
  • 53
  • 75
1

This is valid syntax for C# 8. The syntax constrains T to be a nullable reference type

Jonesopolis
  • 25,034
  • 12
  • 68
  • 112
0

I haven't seen some things mentioned. And it's a bit counter-intuitive at first since we all know reference types can be null. This feature really answers should they be null.

"Nullable reference type" basically states your intent that null is a valid value, both to those reading the code and to the compiler.

It helps to protect you from doing things like string shouldntBeNull = null;.

Which you can spot if you enable this feature using <Nullable>enable</Nullable> in the project settings.

In contrast, this shows intent more clearly string? couldBeNull = null;

This is an opt-in feature.

Zer0
  • 7,191
  • 1
  • 20
  • 34