This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is wrong in comparing a null with an object rather than an object with a null
I see some developers using the following null object checking in C#:
if (null == myObject)
{
}
rather than:
if (myObject == null)
{
}
I prefer the second statement, since it reads naturally (for me) from left to right.
Is there any reason for why the first one would be used? Are there any performance benefits, or is it purely taste?
Some people (Mostly C developers) prefer the first way because if you forget one = sign the code wont compile in C.
For example, when i forget one =;
int a = 0;
if(a=1) //Accidental assignment, luckily the C# compiler warns us for this. The C compiler wouldnt.
{
}
if(1=a) // This is not logical, and not valid in either C# or C.
{
}
However as Jamietre pointed out that unlike C its invalid in C# to implicitly cast an int to a boolean. The compiler still produces an error. It will however work when you compare booleans as such: if(a == true). However that in itself is rather odd, as you can (and should in my opinion) omit the == true.
Purely taste. They both will return exactly the same thing.
Pure taste, same as with comas, brackets etc.
Related
This question already has answers here:
c# casting with is and as
(5 answers)
Closed 6 years ago.
In C# there is is operator for checking if object is compatible with some type. This operators tries to cast object to some type and if casting is successful it returns true (or false if casting fails).
From Jeffrey Richter CLR via C#:
The is operator checks whether an object is compatible with a given
type, and the result of the evaluation is a Boolean: true or false.
if (o is Employee)
{
Employee e = (Employee) o;
// Use e within the remainder of the 'if' statement.
}
In this code, the CLR is actually checking the object’s type twice:
The is operator first checks to see if o is compatible with the
Employee type. If it is, inside the if statement, the CLR again
verifies that o refers to an Employee when performing the cast. The
CLR’s type checking improves security, but it certainly comes at a
performance cost, because the CLR must determine the actual type of
the object referred to by the variable (o), and then the CLR must walk
the inheritance hierarchy, checking each base type against the
specified type (Employee).
Also, from the same book:
Employee e = o as Employee;
if (e != null)
{
// Use e within the 'if' statement.
}
In this code, the CLR checks if o is compatible with the Employee
type, and if it is, as returns a non-null reference to the same
object. If o is not compatible with the Employee type, the as operator
returns null. Notice that the as operator causes the CLR to verify an
object’s type just once. The if statement simply checks whether e is
null; this check can be performed faster than verifying an object’s
type.
So, my question is: why do we need is operator? Which are the cases when is operator is more preferable over as.
why do we need is operator?
We don't need it. It is redundant. If the is operator were not in the language you could emulate it by simply writing
(x as Blah) != null
for reference types and
(x as Blah?) != null
for value types.
In fact, that is all is is; if you look at the IL, both is and as compile down to the same IL instruction.
Your first question cannot be answered because it presumes a falsehood. Why do we need this operator? We don't need it, so there is no reason why we need it. So this is not a productive question to ask.
Which are the cases when is operator is more preferable over as.
I think you meant to ask
why would I write the "inefficient" code that does two type checks -- is followed by a cast -- when I could write the efficient code that does one type check using as and a null check?
First of all, the argument from efficiency is weak. Type checks are cheap, and even if they are expensive, they're probably not the most expensive thing you do. Don't change code that looks perfectly sensible just to save those few nanoseconds. If you think the code looks nicer or is easier to read using is rather than as, then use is rather than as. There is no product in the marketplace today whose success or failure was predicated on using as vs is.
Or, look at it the other way. Both is and as are evidence that your program doesn't even know what the type of a value is, and programs where the compiler cannot work out the types tend to be (1) buggy, and (2) slow. If you care so much about speed, don't write programs that do one type test instead of two; write programs that do zero type tests instead of one! Write programs where typing can be determined statically.
Second, there are situations in C# where you need an expression, not a statement, and C# unfortunately does not have "let" expressions outside of queries. You can write
... e is Manager ? ((Manager)e).Reports : 0 ...
as an expression but pre C# 7 there was no way to write
Manager m = e as Manager;
in an expression context. In a query you could write either
from e in Employees
select e is Manager ? ((Manager)e).Reports : 0
or
from e in Employees
let m = e as Manager
select m == null ? 0 : m.Reports
but there is no "let" in an expression context outside of queries. It would be nice to be able to write
... let m = e as Manager in m == null ? 0 : m.Reports ...
in an arbitrary expression. But we can get some of the way there. In C# 7 you'll (probably) be able to write
e is Manager m ? m.Reports : 0 ...
which is a nice sugar and eliminates the inefficient double-check. The is-with-new-variable syntax nicely combines everything together: you get a Boolean type test and a named, typed reference.
Now, what I just said is a slight lie; as of C# 6 you can write the code above as
(e as Manager)?.Reports ?? 0
which does the type check once. But pre C# 6.0 you were out of luck; you pretty much always had to do the type check twice if you were in an expression context.
With C# 7 operator is can be less wordy then as
Compare this
Employee e = o as Employee;
if (e != null)
{
// Use e within the 'if' statement.
}
and this
if (o is Employee e)
{
// Use e within the 'if' statement.
}
Information from here. Section Pattern Matching with Is Expressions
There are times when you might want to just check the type not actually go through the effort of casting it.
As such you can just use the is operator to confirm your object is compatible, and do whatever logic you want. Whereas in other scenarios you may just want to cast (Safely or otherwise) and utilise the returned value.
Ultimately because is just returns a boolean, you can use it for checking.
as and the (T)MyType type casting are used to safely casting to null, or throwing an Exception respectively
How to: Safely Cast by Using as and is Operators (C# Programming Guide)
At least one use-case I can think of is when comparing if a certain variable is a value type (as cannot be used in that case).
For instance,
var x = ...;
if(x is bool)
{
// do something
}
It can also be useful when you don't necessarily need to use the cast, but are simply interested whether or not something is of a certain underlying type.
This question already has answers here:
Casting vs using the 'as' keyword in the CLR
(18 answers)
Closed 9 years ago.
How does the "is" operator work in C#?
I have been told that this :
if (x is string)
{
string y = x as string;
//Do something
}
is not as good as this:
string y = x as string;
if (y != null)
{
//Do something
}
Which is better and why?
FxCop issues Warning CA1800 in the first scenario (and not only when using as, but also when using an unchecked cast) as both is and the actual casts require certain type checking operations to determine whether the cast is successful or whether to throw an InvalidCastException.
You might save a few operations by just using as once and then checking the result for null if you are going to use the cast value anyway, rather than checking explicitly with is and then casting anew.
I think second is better cause in first case it will cast object 2 times, first time with is operator and second time in as operator.
while in second case it cast only one time.
The is operator checks if an object can be cast to a specific type or not
like
if (someObj is StringBuilder)
{
StringBuilder ss = someObj as StringBuilder
....
}
The as operator cast an object to a specific type, and returns null if it fails.
like
StringBuilder b = someObj as StringBuilder;
if (b != null) ...
I would use the first approach when more than one type is expected to be stored in x. (You might be passed a string, or a StringBuilder etc). This would allow for non-exception based handling.
If you are always expecting x to hold a certain type of value, then I would use the second option. The check for null is inexpensive and provides a level of validation.
-- Edit --
Wow. After reading some of the comments below, I started looking for more updated information. There is a LOT more to consider, when using as vs is vs (casting). Here are two interesting reads I found.
Does it make sense to use "as" instead of a cast even if there is no null check? and http://blogs.msdn.com/b/ericlippert/archive/2009/10/08/what-s-the-difference-between-as-and-cast-operators.aspx?PageIndex=1#comments
Both of which seem to be well summarized by Jon Skeet's blog. http://www.yoda.arachsys.com/csharp/faq/#cast.as
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Conditional Statements difference
I wanted to know what is a good way of writing the code :
X != null
or
null != X
Both of them will do same thing, but sometimes I see people write null != X so I am not sure what is a good way of writing it.
The convention of reversing comparisons as null != X comes mainly from C where
if(X == NULL) {
is easily confused with
if(X = NULL) {
which is a valid statement that overwrites X with NULL instead of checking if it's NULL.
Turning the comparison the other way;
if(NULL == X) {
works just as well, but confusing the equals operator with assignment
if(NULL = X) {
will actually give a compilation error.
Common practice is to have the variable on the left-hand side: X != null. Putting the variable on the right-hand side is often called a "Yoda Condition".
Putting the literal on the left means that if you accidentally use = instead of == the compiler will complain. Also it can save on explicit null checks, for example (in Java)
if("hello".equals(someString))
returns false if someString is null.
I always use the format
<VAR> (!)= <VAL>
and never invert the order.
As you already said, both of them will do the same thing. The questions is about style so. Personally I would say x!=null is more readable.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
== Operator and operands
Possible Duplicates:
Is there any difference between if(a==5) or if(5==a) in C#?
== Operator and operands
Ok, this may be stupid question, but searching in google (cant seem to ACTUALLY search for an exact phrase even with quotes)
What if any difference is there between
if(false == <somecondition>){
and
if(<somecondition> == false){
in C#? I am familiar with c#'s expression evalution, and understand how the order would make sense if you were doing something like:
if(AccountIsInvalid || AccountIsUnregistered)
I dont need a huge lesson, but would like to understand why some people prefer to do things with false==.... route.
Personally, I never compare anything to false or true.
I would go with:
if (!somecondition)
or:
if (somecondition)
In C there would have been, perhaps, some reason to do this as you could easily make a mistake and use the assignment operator instead of the comparison operator, but in C# it shouldn't make any difference -- you'll get a compile warning if you use the assignment operator. If the assignment were a different type (say int), it would result in an error, since the result wouldn't be a legal expression for the if statement.
I would prefer it to be
if (!<somecondition>)
{
...
}
rather than a comparison to false (or true, for that matter).
Before performing any optimizations or short-circuits, the compiler needs to resolve <somecondition> to true or false value, thus there is no reason why the compiler would evaluate the expressions <somecondition> == false and false == <somecondition> any differently.
This must surely be an issue of style, and style only.
This doesn't matter in C# like it does in c/c++ because conditions must evaluate to a boolean.
In c#, is there any difference in the excecution speed for the order in which you state the condition?
if (null != variable) ...
if (variable != null) ...
Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.
If there is no difference, what is the advantage of the first one?
It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):
// Probably wrong
if (x = 5)
when you actually probably meant
if (x == 5)
You can work around this in C by doing:
if (5 == x)
A typo here will result in invalid code.
Now, in C# this is all piffle. Unless you're comparing two Boolean values (which is rare, IME) you can write the more readable code, as an "if" statement requires a Boolean expression to start with, and the type of "x=5" is Int32, not Boolean.
I suggest that if you see this in your colleagues' code, you educate them in the ways of modern languages, and suggest they write the more natural form in future.
There is a good reason to use null first: if(null == myDuck)
If your class Duck overrides the == operator, then if(myDuck == null) can go into an infinite loop.
Using null first uses a default equality comparator and actually does what you were intending.
(I hear you get used to reading code written that way eventually - I just haven't experienced that transformation yet).
Here is an example:
public class myDuck
{
public int quacks;
static override bool operator ==(myDuck a, myDuck b)
{
// these will overflow the stack - because the a==null reenters this function from the top again
if (a == null && b == null)
return true;
if (a == null || b == null)
return false;
// these wont loop
if (null == a && null == b)
return true;
if (null == a || null == b)
return false;
return a.quacks == b.quacks; // this goes to the integer comparison
}
}
Like everybody already noted it comes more or less from the C language where you could get false code if you accidentally forget the second equals sign. But there is another reason that also matches C#: Readability.
Just take this simple example:
if(someVariableThatShouldBeChecked != null
&& anotherOne != null
&& justAnotherCheckThatIsNeededForTestingNullity != null
&& allTheseChecksAreReallyBoring != null
&& thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded != null)
{
// ToDo: Everything is checked, do something...
}
If you would simply swap all the null words to the beginning you can much easier spot all the checks:
if(null != someVariableThatShouldBeChecked
&& null != anotherOne
&& null != justAnotherCheckThatIsNeededForTestingNullity
&& null != allTheseChecksAreReallyBoring
&& null != thereSeemsToBeADesignFlawIfSoManyChecksAreNeeded)
{
// ToDo: Everything is checked, do something...
}
So this example is maybe a bad example (refer to coding guidelines) but just think about you quick scroll over a complete code file. By simply seeing the pattern
if(null ...
you immediately know what's coming next.
If it would be the other way around, you always have to scan to the end of the line to see the nullity check, just letting you stumble for a second to find out what kind of check is made there. So maybe syntax highlighting may help you, but you are always slower when those keywords are at the end of the line instead of the front.
I guess this is a C programmer that has switched languages.
In C, you can write the following:
int i = 0;
if (i = 1)
{
...
}
Notice the use of a single equal sign there, which means the code will assign 1 to the variable i, then return 1 (an assignment is an expression), and use 1 in the if-statement, which will be handled as true. In other words, the above is a bug.
In C# however, this is not possible. There is indeed no difference between the two.
In earlier times, people would forget the '!' (or the extra '=' for equality, which is more difficult to spot) and do an assignment instead of a comparison. putting the null in front eliminates the possibility for the bug, since null is not an l-value (I.E. it can't be assigned to).
Most modern compilers give a warning when you do an assignment in a conditional nowadays, and C# actually gives an error. Most people just stick with the var == null scheme since it's easier to read for some people.
I don't see any advantage in following this convention. In C, where boolean types don't exist, it's useful to write
if( 5 == variable)
rather than
if (variable == 5)
because if you forget one of the eaqual sign, you end up with
if (variable = 5)
which assigns 5 to variable and always evaluate to true. But in Java, a boolean is a boolean. And with !=, there is no reason at all.
One good advice, though, is to write
if (CONSTANT.equals(myString))
rather than
if (myString.equals(CONSTANT))
because it helps avoiding NullPointerExceptions.
My advice would be to ask for a justification of the rule. If there's none, why follow it? It doesn't help readability
To me it's always been which style you prefer
#Shy - Then again if you confuse the operators then you should want to get a compilation error or you will be running code with a bug - a bug that come back and bite you later down the road since it produced unexpected behaviour
As many pointed out, it is mostly in old C code it was used to identify compilation error, as compiler accepted it as legal
New programming language like java, go are smart enough to capture such compilation errors
One should not use "null != variable" like conditions in code as it very unreadable
One more thing... If you are comparing a variable to a constant (integer or string for ex.), putting the constant on the left is good practice because you'll never run into NullPointerExceptions :
int i;
if(i==1){ // Exception raised: i is not initialized. (C/C++)
doThis();
}
whereas
int i;
if(1==i){ // OK, but the condition is not met.
doThis();
}
Now, since by default C# instanciates all variables, you shouldn't have that problem in that language.