Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I wish to know if there's some way to know which is the elemnet of a logic operation is false?
Example.

if( String.IsNullOrEmpty(obj1) || (String.IsNullOrEmpty(obj2) )
   throw("..............."); 

How can I kown which one of those is the empty one?

share|improve this question
1  
To handle the condition results for each case separately, the better way is to write 2 nested if statements . any other way will either be more complex or add more variables or methods but no real value to the code quality or to the execution speed. –  Emmad Kareem Mar 11 '12 at 13:00
add comment

3 Answers

You cannot know which one of the subexpressions is empty, unless you repeat the checks.

Alternatively, you can separate the above code into two separate if statements, duplicating the throw("...") part.

share|improve this answer
add comment

You can't know that in your code. But you can simply create two variables, that contain the parts of the condition and then check which one of them is true (at least one of them will) and which false (at most one of them).

bool isObj1Empty = String.IsNullOrEmpty(obj1);
bool isObj2Empty = String.IsNullOrEmpty(obj2);
if (isObj1Empty || isObj2Empty)
   throw("...............");
share|improve this answer
add comment

This almost belongs on CodeReview. Here is how I would deal with this fairly cleanly, without checking things twice:

public void DoSomething(string obj1, string obj2)
{
    CheckStrArgNotEmpty(name: "obj1", value: obj1);
    CheckStrArgNotEmpty(name: "obj2", value: obj2);

    // Optionally:
    obj1 = obj1.Trim(); // obj1, obj2 are bad names btw
    obj2 = obj2.Trim();

    // The rest of the code ...
}

private static CheckStrArgNotEmpty(string argName, string value)
{
    if (!String.IsNullOrWhitespace(value)) // or IsNullOrEmpty ?
    {
        return;
    }

    string exceptionMessage = String.Format(
        "Argument named '{0}' is null or empty but it should not have been."
        argName);
    throw new ArgumentException(message: exceptionMessage);
}
share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.