Difference between Forward and Reverse Comparison in C#
this is related to comparing values in C#.
basically by def开发者_JAVA百科ault, in C# till date i only used forward comparison as follows:
string value1 = "";
if (value1 == null)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
somewhere on Internet, i came across a link where it is said that while comparing values in C#, we should prefer Reverse Comparison as :
string value1 = "";
if (null == value1)
{
Console.WriteLine("True");
}
else
{
Console.WriteLine("False");
}
Now the problem is that is there any basic difference between the two ways of comparing values or not (i.e. both are same).
Looking for favorable replies.
Thanks
This is a hangover from languages where values are implicitly converted to a boolean type.
For the most part, anything that was non-null
or non-0
would be treated as true
, otherwise it was equivalent to false
. This meant that any assignation of a constant would always be true
.
This thing to remember here is that the assignment function returns the value assigned, much in the same way that 5
is the result of 2+3
, myInt = 5
also returns 5
.
Because of this, it was recommended that you check the variable against the constant. The null
example is actually probably a bit contrived in this case, as it would, in most languages, return as false.
As an example:
if(i = 1)
{
printf("Always out\n");
}
else
{
printf("Never prints\n");
}
i
is assigned the value of 1
, which then returns the value of the assignment, 1
, to the if
statement. This is equivalent to true
, and the if
condition matches.
If you were to attempt to assign i
to the constant 1
, you wouldn't compile, and so it was recommended that you do things it that order (e.g. 1 == i
).
This is not neccesary in C#, and further to your example, the recommended practice is to call if(String.IsNullOrEmpty(myStringValue)) { //.... }
, as a string has... two ... default values from a semantic perspective.
Reverse comparison protects you from errors, when you use ==
(compare) instead of =
(assign). But complier also warns you if you do this.
精彩评论