0

I'm new to C#, I've seen some people write string? SomeVar; in YouTube. I just want to know what is the use of the ? symbol.

I've tried to Google it but I didn't get anything I wanted.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • 2
    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/builtin-types/nullable-value-types – Franz Gleichmann May 02 '23 at 15:32
  • 2
    @FranzGleichmann `string` is not a value type. – Joe Sewell May 02 '23 at 15:39
  • 2
    Does this answer your question? [What is the purpose of a question mark after a value type (for example: int? myVariable)?](https://stackoverflow.com/questions/2690866/what-is-the-purpose-of-a-question-mark-after-a-value-type-for-example-int-myv) (that link is in the top then of a simple search result: https://stackoverflow.com/search?q=%5Bc%23%5D+question+mark+) – Luuk May 02 '23 at 15:41
  • 3
    Better duplicate link if there are any gold-badgers around https://stackoverflow.com/questions/69433546/what-does-a-question-mark-after-a-reference-type-mean-in-c – Charlieface May 02 '23 at 15:46

2 Answers2

2

C# 8 has introduced a new feature called nullable reference types:

In a nullable oblivious context, all reference types were nullable. Nullable reference types refers to a group of features enabled in a nullable aware context that minimize the likelihood that your code causes the runtime to throw System.NullReferenceException. Nullable reference types includes three features that help you avoid these exceptions, including the ability to explicitly mark a reference type as nullable:

  • Improved static flow analysis that determines if a variable may be null before dereferencing it.
  • Attributes that annotate APIs so that the flow analysis determines null-state.
  • Variable annotations that developers use to explicitly declare the intended null-state for a variable.

So string? denotes a nullable string which allows compiler to emit appropriate warnings when developer does not perform appropriate checks to reduce NREs.

Note that there is another similar feature - nullable value types which is a bit different (which worth a separate discussion =).

Read more:

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
0

? means that the field\property can be null. string? is a nullable string, int? is a nullable int and so on.

Lior v
  • 464
  • 3
  • 12
  • The `?` on a value type like int _"means that the field\property can be null"_. The use of `?` on a reference type is much more nuanced. Remember that `string someNullString = null;` is perfectly good code. – Flydog57 May 02 '23 at 16:37