-2

What is the difference between these operators?

var c = foo?.Prop1;

var c = foo!.Prop1;

Btw, Prop1 is an int.

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
Alp
  • 358
  • 5
  • 12
  • 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. – Tim Schmelter Oct 24 '22 at 14:01

1 Answers1

4

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)
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215