jeudi 19 novembre 2020

C# Determine which condition was satisfied

In my C# code I'm having the following code:

if (A == null)
{
    errors.Add(nameof(A), "A does not exist.");
    return Task.CompletedTask;
}
else if (B == null)
{
    errors.Add(nameof(B), "B does not exist.");
    return Task.CompletedTask;
}

where types A and B are treated identically. I am therefore experimenting if these conditions can be merged to obtain more concise code!

Would it be possible to write something like

if (A == null || B == null)
{
    errors.Add(nameof(A/B), "A/B does not exist."); // When A == null, use A. When B == null, use B.
    return Task.CompletedTask;
}

where we can retrieve information about which type is null? In other words, can we find out which of the conditions in the if-statement was satisfied?

Thanks in advance!

Aucun commentaire:

Enregistrer un commentaire