C#C
C#3y ago
LastExceed

❔ null warning while indexing (rather than accessing) null-agnostic type?

first, lets look at a scenario where everything behaves as expected:
string[]? GetList() => throw new NotImplementedException();

var myList = GetList();
string a = myList.ElementAt(0); //null warning while accessing `myList` - as expected
string b = myList[0]; //same thing here - as expected
string c = myList[0]!; //this doesn't change anything, because its not the indexer but the variable that is nullable - as expected
string c = myList![0]; //this successfully suppresses the warning - as expected

but if we move GetList to another project that doesn't use nullables:
#nullable disable //basically any project up until C# 7.3
namespace Foo;

public static class Stuff
{
    public static string[] GetList() => throw new NotImplementedException();
}

now we get the following behaviour:
using Foo;

var myList = Stuff.GetList();
string a = myList.ElementAt(0); //no warning at all, despite having configured interpretation of null-agnostic types to be pessimistic - weird but whatever
string b = myList[0]; //here we DO get a null warning (dunno why this makes a difference), however its not while accessing the variable (where i would expect one), but while INDEXING it - wtf?
string c = myList[0]!; //this suppresses that warning - ok, but why was it there in the first place?
string d = myList![0]; //this doesn't.

can someone explain?
Was this page helpful?