-1
  List<int> testList;
// <some processing which loads data into testList>
  var x = testList![4];
  var y = testList!?[3];

The compiler doesn't throw error . x is resolved as int. y is resolved as int?. What does ! operator mean in this case (in case there is a ? after it)

How is !? interpreted by the compiler? Is the null forgiving operator neglected at run-time? What happens if the itemsList is null in run-time?

Is it okay to guess that !? is considered as ? in runtime?

Abhijith C R
  • 1,440
  • 1
  • 12
  • 12
  • 1
    Have reopened the question. I dont think this is a duplicate question on null forgiving operator, but more a question on operator precedence when you use `!` and `?` together. I myself haven't seen that before and was amused. Would like to know what C# spec has to say about this. – nawfal Dec 07 '21 at 05:24

1 Answers1

2

Ah, that one is - interesting.

C# 8, Null Forgiving operator.

Basically you tell the code analyzer the value WILL NOT BE NULL (testList).

Which - given the code example - is not sensible at is will not be null anyway.

TomTom
  • 61,059
  • 10
  • 88
  • 148
  • It can still be null at runtime if assigned, right? Refer https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/null-forgiving – Abhijith C R Dec 06 '21 at 18:10
  • I never said that is not the case - just in the example, it is only assigned ONCE and with a value, so it can not be null. The code analyzer should see this. – TomTom Dec 06 '21 at 18:55
  • Forget the sample assignment provided to testList please. I have edited the question to avoid confusion. Assume that testList can be null or non null. – Abhijith C R Dec 06 '21 at 19:14
  • Yeah. The !" will quiet the code analyzer - it will not magically make the null pointer exception go away. – TomTom Dec 06 '21 at 20:29