In a If Statement When should I use =, == operators. Is there a === operator ? What is the difference between these operators ?
-
4What book are you using to learn C#? This should be covered in the first chapter or two.– Greg HewgillJan 16, 2011 at 8:05
-
Sorry cant tell you the name of the book , it would be like offending the author :). Its Sad some examples are not explained well in this book :(– subankiJan 16, 2011 at 8:10
-
3@subanki: If you regard the book that poorly, get a different one. What's the point of wasting your time trying to learn a language from a book that even you agree is so bad it would embarrass the author? See this question, and this other question for some recommendations.– Cody Gray - on strike ♦Jan 16, 2011 at 8:14
-
@Cody The book is very simple and easy to understand but some few examples are not explained well . Besides I just bought this book 2 days ago.– subankiJan 16, 2011 at 8:20
-
@subanki: That's good: it means you haven't wasted very much time on the book already. If the simple examples are poorly explained, what can you possibly expect for the more complicated stuff? I suspect it will just get much worse. There are other simple books that are easy to understand—the questions I linked to suggest books for a new programmer, not experts.– Cody Gray - on strike ♦Jan 16, 2011 at 8:24
12 Answers
= is assignment, like in
var i = 5;
Do not use this operator in the if statement.
== is for comparison like in
if(i == 6){...}
there is no === operator in C#
-
So if I use it like this ......... if (i = 5) {x=10;} ...... in this case the i is being assigned the value 5 ?– subankiJan 16, 2011 at 8:14
-
2C# is smart enough to warn you when you try to compile that code. it should be if (i == 5) {x = 10;} EDIT: Clarifications– tenorJan 16, 2011 at 8:16
-
3No warning just a error, i=5 will be evaluated, i will be assigned the value 5 and return 5, as 5 is not a boolean (true/false) the if statement is illegal and you will get a compilation error.– ViktorJan 16, 2011 at 8:25
-
1C# won't compile it, because i = 6 does not evaluate to a boolean expression. Even if it did, assigning a variable inside an if condition block is bad style and should be avoided.– tenorJan 16, 2011 at 8:27
-
1+1, @Viktor that's right a compilation error will show and the program won't execute. Jan 16, 2011 at 8:30
(The following is somewhat of a "comment" but is too long to be in a comment and would be lost with the other comments in this post.)
In C# == (like all operators in C#) is non-polymorphic. That is, the "version" of == that is called is always based on the static type at compile-time.
For instance:
object a = Guid.NewGuid();
object b = new Guid(""+a);
a == b // false -- uses object.== -- an *identity* compare
The Equals virtual method, on the other hand, is defined on object and is thus polymorphic across all sub-types.
object a = Guid.NewGuid();
object b = new Guid(""+a);
a.Equals(b) // true -- uses Guid.Equals
The choice of which one to use (== or Equals) is sometimes subtle -- but important. Most collection types will use Equals for tasks like Contains, etc. (This is pretty much required for all generic containers as there is no T.== for an arbitrary type T.)
// compile-time error: Operator '==' cannot be applied to operands of type 'T' and 'T'
bool equals<T> (T a, T b) { return a == b; }
// fair-game, because object defines Equals and it's polymorphic to subtypes
bool equals<T> (T a, T b) { return a.Equals(b); }
See When should I use == and when should I use Equals? and Guidelines for Implementing Equals and the Equality Operator (==), etc. Personally, I use == over Equals for statically-resolvable concrete types for which == is well-defined and I will not (by contract or convention) deal with a subtype -- examples are string and (most) structure types (e.g. int, Guid).
Happy coding.
Edit: There is no C# === operator (as people have said, duh!). If talking about the JavaScript variant, it would be approximately:
bool trippleEquals (object a, object b) {
return a.GetType() == b.GetType() && a.Equals(b);
}
(It is strict equality in JavaScript -- but not object identity).
If talking about object identity then it should be the same as (object)a == (object)b which has the same semantics as object.ReferenceEquals(a,b).
-
+1 for showing the difference between strict equality and object identity.– comecmeJan 16, 2011 at 11:47
a single = is for assignment like:
String myString = "Hi There";
A double equal is for comparison
if (5 == 5)
{
do something
}
triple equals in some languages mean exactly equal.
C# does not utilize that operator.
In addition to the other answers, ReferenceEquals(x,y) is probably the closest thing to ===.
In if statement you usually check for equality using ==, the = operator is the assignemt operator, and for my knowledge there is no === in c# I have never heard of it but it does exists in other languages I think in javascript it does.
This is to long for a comment so I decided to add another post.
I set var variables to an object list this and performed a comparison on the two vars that always failed comparison logic:
object Object1;
object Object2;
var v1 = Object1;
var v2 = Object2;
if (v1 != v2)
{
// Do something
}
Thanks to the posts here in this thread, I changed the logic as follows and now it works perfectly:
object Object1;
object Object2;
var v1 = Object1;
var v2 = Object2;
if (!v1.Equals(v2))
{
// Do something
}
One equal sign is only used to assign a variable a value, the assignment will also return the same value so i could be used in a if statement but should never (almost...) be used in a if statement. Double equal signs are used to test if two values are equal and is what you use most of the time. I don't know of a === operator.
/Viktor
= is an assignment operator while
==is an comparision operator
Example:
int a=2;
int b=3;
int c=a=b; // a, b, c is equal to 3 as b=3
while
int a=2;
int b=3;
bool c= a==b // c = false since result of a==b is false
For extra info, the Not Equal operator is !=.
More info on C# Operators: http://msdn.microsoft.com/en-us/library/6a71f45d%28v=VS.100%29.aspx
I came across === only in javascript yet. It's the strict equal operator in there.
I used it several times as this if(obj === undefined){ alert("obj has sublimed");}
-
Pretty sure you meant: if(typeof obj === 'undefined'){ alert("obj has sublimed");} --- your example, by definition, returns a reference error– CarnixJun 1, 2017 at 18:28
-
@Carnix Yes you are correct,
(typeof obj === 'undefined')is the best way to use it. Also, it's been years that I posted that answer :-D and have learnt more till today than what I knew in 2011.– v1pJun 3, 2017 at 13:35
The question has since been answered, but I wanted to go into a little further detail between the uses.
"=" is an assignment operator. This is used to assign a value (or values) to a variable or object. An example of this would be:
int abc;
abc = 5;
Console.WriteLine("Print: " + abc);
*Console Output* Print: 5
You can't use a single equal sign in an if statement as the code would see you trying to assign a value to the object instead of comparing two values.
"==" is a comparison operator. This is the way you would compare values in an if statement. An example would be:
int abc = 5;
int xyz = 10; //Notice the use of a single equal sign to assign the values
if (abc == xyz)
{
Console.WriteLine("The values are equal");
}
else
{
Console.WriteLine("The values are not equal");
}
*Console Output* The values are not equal
"===" would technically be called an identical comparison operator. As the other answers have stated, C# does not allow for this sort of comparison. The reason it won't is because the identical comparison operator is checking whether the two object types are equal as well as their value. Essentially, it would check whether:
double abc = 5;
int xyz = 5;
if (abc === xyz)
{
Console.WriteLine("The values and variable types are equal");
}
*Console Output* Error
The reason you can't use the "===" operator is because C# is smart enough to know before a build that the two variables are not the same type and if statements require you to compare the same variable types. IF you wanted to compare an int vs. double, you would need to cast (or parse) one of the variables to be the same type as the other. After casting, you would then compare with the regular "==" operator.
There are many languages that do allow you to compare with the identical comparison operators. JavaScript is an excellent example of a language that does allow for it. Since so many variables in JavaScript can be declared as a "var" type, it is beneficial to check whether a decimal value is equal to an integer value. C# however, will see the types being compared incorrectly during a build or even while coding (depending on your IDE) and will throw an error or exception when it reaches that piece of code
= and == means fundamentally different things in the C# programming language. = is the assignment operator. It is used to assign values to variables.
The variable being the bucket in the computer memory and the assignment operator being the sign used to tell the computer to put some data in the bucket.
== is the equality operator it is used to determine if variable is equal to another variable. === is the operator for strict equality, this checks not only that what is in the bucket is the same, but that the type of variable is also the same, so for instance...
if you have a integer variable that is equal to 6 and a string that is equal to 6 if you check equality with ==, then the check will give a Boolean value of true, if you do it with === it will give a false.
This is useful in weakly typed programming languages, like JavaScript where implicit type conversions are common and you sometimes need to check for types and values during equality checks.
Seeing as C# you declare types when you declare your variables there is no way you would not, not know what a variables type is. Also, the CLR for C# is very strict in what type-conversion it allows and for such a type casting to happen you have to explicitly convert it. All of which makes a strict equality operator redundant to a large degree.
In decision structures, like loops, you will not use the assignment operator. Typically you will have your variables already defined and populated with data when you do these checks, you would use equality operator (Among others).
-
"but that the type of variable is also the same" This is true in JavaScript, but not in C#. Jun 14 at 17:50