Samee Daris
Samee Daris

Reputation: 78

Validation multiple properties required one

I am looking for better way to solve following scenario. I don't want to use reflection for now and was to take logic to nth level. Code should be simple C# no attribute validations. Because this is back-end code validation. I would love to solve this some operator like XOR or similar.

Scenario:

I have three fields (can be 4, 5, nth) in a class. out of three user must select only one field either of them. if none, two or more fields are selected we need to throw exception.

Code:

// no type defined for item
if ( hasUserId==false
    && hasSigningGroup==false
    && hasAssignedAgent == false)
{
    throw new Exception("No type defined for item.");
}
else
{
    if ((hasSigningGroup && hasUserId)|| (hasSigningGroup && hasAssignedAgent)|| (hasUserId && hasAssignedAgent))
    {
        throw new Exception("User ID , Signing group or assigned agent. Only one property can be set.");
    }
}

Upvotes: 2

Views: 789

Answers (2)

Samee Daris
Samee Daris

Reputation: 78

Guys I found easy way to solve this issue .This will work in all cases. Neither XOR nor != operators were working.

            int result = Convert.ToInt32(hasUserId) + Convert.ToInt32(hasSigningGroup) + Convert.ToInt32(hasAssignedAgent);

            if (result != 1)
            {
                throw new Exception("User ID , Signing group or assigned agent. Please set one property.");
            }

Thanks

Upvotes: 0

Carson
Carson

Reputation: 894

https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/boolean-logical-operators Logical exclusive OR operator ^

"The ^ operator computes the logical exclusive OR, also known as the logical XOR, of its operands. The result of x ^ y is true if x evaluates to true and y evaluates to false, or x evaluates to false and y evaluates to true. Otherwise, the result is false. That is, for the bool operands, the ^ operator computes the same result as the inequality operator !=."

You could also use !=.

I believe this is what you are looking for.

Edit: removed code example due to logical flaw. Answer is still ^ or != as an XOR operator.

Upvotes: 3

Related Questions