1

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?

  • 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. – NoChance Mar 11 '12 at 13:00
3

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.

| improve this answer | |
3

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("...............");
| improve this answer | |
1

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);
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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