简体   繁体   中英

Using equal operators in C#

In a If Statement When should I use =, == operators. Is there a === operator ? What is the difference between these operators ?

= 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#

(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 (eg 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) .

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.

除了其他答案之外, ReferenceEquals(x,y)可能是最接近===东西。

在 if 语句中,您通常使用 == 检查相等性,= 运算符是赋值运算符,据我所知,c# 中没有 === 我从未听说过它,但它确实存在于其他语言中,我认为在 javascript 中它确实。

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");}

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM