So I have this code:
foreach (var user in ServersHolder.Servers.Find(f => f.ID == 9999).Online.FindAll(g => g.LoginPhase == 3))
{
await trySendPacket(9999, user.GUID.ToString(), OpCode.SentNotifyUserLeft, "", 2);
}
And I have seen where people use ?., I believe in case of a null return like below, but the below doesn't work in that case.
foreach (var user in ServersHolder.Servers?.Find(f => f.ID == 9999).Online?.FindAll(g => g.LoginPhase == 3))
{
await trySendPacket(9999, user.GUID.ToString(), OpCode.SentNotifyUserLeft, "", 2);
}
Could somebody expain? Or is it best practice to do it this way:
if (ServersHolder.Servers.Exists(f => f.ID == 9999))
{
foreach (var user in ServersHolder.Servers.Find(f => f.ID == 9999).Online.FindAll(g => g.LoginPhase == 3))
{
await trySendPacket(9999, user.GUID.ToString(), OpCode.SentNotifyUserLeft, "", 2);
}
}
ServersHolder.Serversis not handled with the null checking.ServersHolder.Serverscould be null, I doubt you will get the Null Reference Exception in the loop if it is null. Thus you have to provide a default value when it is null with emptyIEnumerable<YourType>foreach (var user in ServersHolder.Servers?.Find(f => f.ID == 9999).Online?.FindAll(g => g.LoginPhase == 3) ?? new List<User>)