Search code examples
c#nullnullable

c# what is the difference between "!" operator and "?" operator?


What is the difference between these operators?

var c = foo?.Prop1;

var c = foo!.Prop1;

Btw, Prop1 is an int.


Solution

  • 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)