I am running an asp.net core application , I have a class with a string array member which i have declared as nullable. When i am using the array elements in my other classes, the compiler gives me Dereference of a possibly null reference warning only for the first member of the array and not for the others.
PS sorry for bad formatting of the code. There are no syntax errors
I am getting a warning for possible null values for DummyData[0] but not for DummyData[1] and others.
public class Dummy
{
public string[]? DummyData { get; set; }
}
This is where i am using DummyData
result += DummyDataConstants.SOM + DummyDataConstants.cmdMainArray[(int)DummyDataConstants.CMD_MAIN_ID_e.CMD_MAIN_REQ_LOG]
+ DummyDataConstants.FSP + DummyDataConstants.SMART_CODE + DummyDataConstants.FSP + commandParams.DummyData[0] // warning given for commandParams.DummyData[0]
+ DummyDataConstants.FSP + commandParams.DummyData[1] // no warning here
+ DummyDataConstants.FSP + commandParams.MediaClientType + DummyDataConstants.FSP + commandParams.DummyData[2] + DummyDataConstants.FSP + newGuid.ToString() + DummyDataConstants.FSP + DummyDataConstants.EOM
Compiler will emit warning only when your code may dereference null
. In this case only place where this is considered to be possible is commandParams.DummyData[0]
since if it is (i.e. commandParams.DummyData == null
) you will encounter NullReferenceException
here, hence all other attempts either will not happen or will work with definitely not null reference. If you will use null-conditional element access operator for the first element you will see the warning "transferred" to the next one:
void WarningTest(int[]? array)
{
Console.WriteLine(array?[0]);
Console.WriteLine(array[0]); // warning
Console.WriteLine(array[0]); // no warning
}