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);
}
}
This question is somewhat subjective…
the
Equalsmethod 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:
In this example, the
Equalsmethod is used to produce a result of the comparison of values in theCustomObjectagainst another instance of the same type. The==operator for CustomObject simply callsEqualson 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 overEquals, 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 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 condition is not boolean by nature and the objects you are comparing do not have the
==or!=operators implemented, then usingEqualsis 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: