2

Having even more than two options to choose from, leads me to question, which one to choose, if the result / outcome is same.

in .NET C# the following conditions are asking same question using different operators, so the question is , what experienced developers use, i tend to assume that ready made operators like Equals would go through more processing actions.

When and why would you choose ! over Equals, and both over 'traditional' == ?

//bool
if (!Page.IsPostBack) 
{
    //bool
    if (NotAuthorized().Equals(false)) 
    {            
        AppsCtrls.DDLs_Init();

        //bool
        if (CurrSeSn.Raised(Flag.MainDataSet_IsPopulated) == false)
        {
            initALLDataSet(AllDataStColsSelectionMod.doneViaSP);
        }

        custid = RConv.Str2int(Request.QueryString["custid"]);
        username = GetTableData.AsString("name", "tblCustomers", "custid", custid);
    }
}
GameScripting
  • 16,092
  • 13
  • 59
  • 98
LoneXcoder
  • 2,121
  • 6
  • 38
  • 76
  • 1
    Check this out: http://stackoverflow.com/questions/3678792/are-string-equals-and-operator-really-same – Josh Nov 07 '12 at 22:09
  • Well, `!` does read the way logic functions are normally read allowed, "If the page is not a post back" or "if you are not authorized" as opposed to "if the page is a postback is equal to false". – Servy Nov 07 '12 at 22:26
  • @Josh Those points are entirely irrelevant as `bool` isn't nullable and can't be extended (so there will be no derived types). – Servy Nov 07 '12 at 22:28
  • @Servy As @LoneXcoder learned, the link provides a reason to use `Equals`, which involves advantages that the comparison operator, `==`, does not have. It wasn't a link to answer his question but provide some additional insight. Definitely not *irrelevant*. – Josh Nov 07 '12 at 22:56
  • @Josh The reason that `==` wasn't working as the OP thought in that case is because the variable was typed as an `object`, not a `string`. If it was typed as a `string` it would have worked fine. On top of that, if it was actual code and not in the immediate window he would have gotten a compiler error for using `==` on both a string and an object, as it's a common error. Again, it's not really relevant when considering booleans. – Servy Nov 08 '12 at 14:24
  • @servy Like I already said, it wasn't an answer to his question, but to provide additional insight. OP asks, When and why would you choose ! over Equals, and both over 'traditional' == ?. The link answers that question, in part. – Josh Nov 09 '12 at 19:51

3 Answers3

2

This question is somewhat subjective...

"i tend to assume that ready made operators like Equals would go through more processing actions."

" when and why would you choose ! over Equals , And both over 'traditional' == "

the Equals method as part of an instance of an object is used to check for equality of that instance against another, whilst the == and != operators are static and are therefore unbound from any object instance. Instead these are like a special static method that accepts two arguments (of usually the same type) and compares them.

Consider the following example:

public class CustomObject
{
    int someValue, anotherValue;    

    public bool Equals(CustomObject obj)
    {
        return (this.someValue == obj.someValue && this.anotherValue == obj.anotherValue);
    }

    public static bool operator ==(CustomObject a, CustomObject b)
    {
        return a.Equals(b);
    }

    public static bool operator !=(CustomObject a, CustomObject b)
    {
        return !(a == b);
    }
}

In this example, the Equals method is used to produce a result of the comparison of values in the CustomObject against another instance of the same type. The == operator for CustomObject simply calls Equals on one of the parameter objects and performs an equality check against the other. The != operator simply negates the == and produces the opposite result. Therefore, == and != do not have much performance overhead over Equals, because they both call that method anyway.

Best practices:

if a condition is boolean by nature there is no need to use Equals, != or ==, but you should use ! to negate a boolean condition.

For example:

if(IsPostBack) // this is good

if(IsPostBack == true) // this is unnecessary

if(!IsPostBack) // this is good

if(IsPostBack == false) // this is unnecessary

If a condition is not boolean by nature, or you are comparing two boolean values, or you are comparing an enumeration, or other value type then use of != or == is acceptable.

For example:

if(a == b) // this is good

if(a != b) // this is good

If a condition is not boolean by nature and the objects you are comparing do not have the == or != operators implemented, then using Equals is acceptable. Note, using != and == are prohibited with generics since it is not known at compile time that != or == are implemented on the objects represented by the generic objects type parameters.

For example:

if(a.Equals(b)) //this is good

if(!a.Equals(b)) // this is good

if(a.Equals(b) == true) // this is unnecessary
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313
1

I typically choose the option that is the shortest, ie:

if (!Page.IsPostBack)

Or:

if (Authorized())

Since C# doesn't allow non-boolean expressions in an if statement, this is perfectly clear, so I see no reason for the extra typing.

That being said, this is really purely a matter of convention and preference - there is no performance advantage to using one form over the other.

This is different than C++, for example, where you can use if (42), in which case seeing if (foo) isn't enough to know whether foo is a boolean, or some other type. In that scenario, it occasionally makes sense to include the condition check (ie: if (foo == false)) as you can then see the type distinctly and make your intentions clear.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • so i guess it's same , when it comes from you, only in your example case i would perfer to make first one be more ... you know for me to know and not missing the! within rest of expression , although in this case usage i would expect it to be there as if ! And Pagepostback was born togethere\ – LoneXcoder Nov 07 '12 at 22:12
  • @LoneXcoder Functionally, they're all the same. Its purely preference in terms of what you want to type. – Reed Copsey Nov 07 '12 at 22:13
0

Use the first. Unlike C/C++ where zero/null == false, in C# only boolean value types can be used with the boolean operators, i.e.:

int i=1;
if (i) { .... }

Will not compile, so there is no need to explicitly test equality of booleans, specially when using descriptive names (IsSomething, HasHappened, NotSomething, etc.)

Eli Algranti
  • 8,707
  • 2
  • 42
  • 50
  • The one exception I've found is with nullable booleans. `if(nullableBool == true)` reads nicer to me than `if(nullableBool??false)` or `if(nullableBool != null && nullableBool.Value)`. – Servy Nov 07 '12 at 22:25