dreadeddev
dreadeddev

Reputation: 268

checking an array of string objects for null values

This is a fairly basic question I think but either my brain hasn't woken up yet or I'm just being thick!

I have a class that has a property of a collection of strings defined below (names are simplified)

public class IdentifierCollection : BaseSubCollection, IIdentifierCollection
{
    public string Id1{ get; set; }
    public string Id2{ get; set; }
    public string Id3{ get; set; }
    // ...      
}

I want to check if any of the properties actually have a value before saving so I am currently doing something like this...

if (string.IsNullOrEmpty(primaryObj.Identifiers?.Id2) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id2) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id3) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id4) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id5) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id6) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id7) &&
    string.IsNullOrEmpty(primaryObj.Identifiers?.Id8))
{

}

Just typing this feels wrong!! There must be a better way...

Upvotes: 0

Views: 83

Answers (1)

Kapol
Kapol

Reputation: 6463

I don't think there is anything wrong with this kind of property checking. Using reflection or implementing some interface just to be able to iterate over the properties looks like overkill to me. Though I agree that such a long statement looks awkward as a conditional check. To make the code more readable I'd extract this check to a separate private method.

if (NoPropIsNullOrEmpty())
{
}

private bool NoPropIsNullOrEmpty()
{
    return !(string.IsNullOrEmpty(primaryObj.Identifiers?.Id2) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id2) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id3) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id4) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id5) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id6) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id7) ||
             string.IsNullOrEmpty(primaryObj.Identifiers?.Id8));
}

Upvotes: 1

Related Questions