-2

What is the difference between these operators?

var c = foo?.Prop1; 

var c = foo!.Prop1; 

Btw, Prop1 is an int.

1
  • 3
    ! tells the compiler: "trust me, this isn't null" but at runtime an exception can happen if you've lied. ? handles a possible null value, so that everything after it is also null. Commented Oct 24, 2022 at 14:01

1 Answer 1

7

Well ? is null conditional when ! is null forgiving operators:

  • ?. in case of full is null do nothing (or return null)
  • !. do not believe that foo can ever be null and stop warning me.

So if foo is null

var c = foo?.Prop1; // c will be null (c will be of type int?) var d = foo!.Prop1; // exception will be thrown (d is int) 
Sign up to request clarification or add additional context in comments.

1 Comment

Also worth mentioning that if Prop1 is an int, than c is a nullable int and d is an int .

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.