This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
C#: String.Equals vs. ==
Are string.Equals() and == operator really same?
sometimes in a condition between two strings, I write:
if(string1==string2) //Do something
and sometimes I write:
if(string1.Equals(string2)) //Do something
The problem is sometimes the first one doesn't work, or miswork, is there any difference between the two expressions?
The first one will always work so long as the compile-time type of both operands is string.
If the compile-time type of either operand is anything other than string, it will use the normal reference identity comparison, rather than comparing strings for equality. Basically you want to call the ==(string, string) overload instead of the normal ==(object, object) overload.
Note that the first will succeed even if string1 is null, whereas the second will throw NullReferenceException in that case. An alternative in order to preserve the Equals call but avoiding this problem is to call the static object.Equals(object, object) method:
if (object.Equals(string1, string2))
Personally I'd just use == in cases where the compile-time types are appropriate though.
The use of == on two string types will perform a reference identity check, meaning it will only return true if both references point to the same object. Equals on the other hand is expected to perform a value comparison, and will return true if the references point to objects that are equivalent.
Related
This question already has answers here:
Is there a way to check if int is legal enum in C#?
(9 answers)
Closed 4 years ago.
pretext:
ChestType is an enum
public enum ChestType
{
COMMON,
GEMNGOLDCHEST,
GODLYCHEST,
ASSCHEST
}
slotAndChestIndex is a ChestType?[]
chestSlotsAndChestsSaved is an int[]
(Sorry for the bad names)
slotAndChestIndex[i] = (ChestType?)chestSlotsAndChestSaved[i] ?? null;
I believe the above line says:
"If I cant cast this int to a ChestType? then express it as null"
ChestType? is however being set to a value of -1 which seems weird to me.
Am I doing something wrong here? Event when I try set it to default(ChestType?) it still sets it to -1 lol. I thought the default of any Nullable type is null.
Please tell me what I'm not understanding!
You can't validate if it is defined within your enum that way; it'll just assign the value of your variable chestSlotsAndChestSaved[i] in it (even though it's -1 and it's not defined in your enum).
The way you can verify this is with:
slotAndChestIndex[i] = (ChestType?)(Enum.IsDefined(typeof(ChestType), chestSlotsAndChestSaved[i]) ? chestSlotsAndChestSaved[i] : (int?)null);
PS: I haven't tested the code, even though, Enum.IsDefined(typeof(ChestType), chestSlotsAndChestSaved[i]) is your way to go.
Neither the ?? operator nor the cast you're doing do quite what you think.
To start with, the cast you've used will never produce a null value - casting from an int to (most) enums will simply produce a value of the type of the enum, but potentially with a numeric value, not one of the enum members. The fact that you cast to ChestType? rather than ChestType doesn't change that. In addition, if a direct cast is performed like you've shown and can't be performed an exception will be raised, and the result will not be null. This should never happen for literal conversions like this, but could happen when casing between classes.
Next, the ?? operator, also known as the null-coalescing operator, evaluates to the left operand if the left operand is not null, and evaluates to the right operand if the left operand is null. So if chestSlotsAndChestSaved[i] was equal to null, the expression would become the right hand operand - however since the right operand is always null, that part of the expression effectively does nothing.
Overall, the most likely reason that slotAndChestIndex[i] is coming back as -1 is because chestSlotsAndChestSaved[i] is -1.
I was looking for the difference between == and .Equals methods in C# and I found that the first one compares the object references, and the second one compares the objects values, except for the string datatypes both == and .Equals() does a content comparison. I can't really find an explanation for that, is it because the string datatypes are immutable ?
Here's what I want to say
object obj1 = "Test";
object obj2 = new string("Test".ToCharArray());
Console.WriteLine(obj1.Equals(obj2) + " " + (obj1 == obj2));
string a = "Test";
string b = "Test";
Console.WriteLine(a.Equals(b) + " "+ (a == b));
Output
True False
True True
In fact for the first comparison we have two different objects with same value and we got as result True and false, but for the case of string we have true for both comparison
This isn't true at all. == is an overridable operator, and Equals is an overridable method. It's up to the class to define how each of them behaves.
Perhaps you're confusing C# with Java?
If you want to do a reference comparison, use object.ReferenceEquals. Everything else is implementation dependant (though note that operator overrides are checked statically, so e.g. (object)someString == (object)someOtherString will do a reference comparison, not a value comparison; Equals doesn't have this "problem").
Most often, both == and Equals are designed to give the same answer (though == is always stricter about types in the comparison, as mentioned before). This applies double for structs, where a reference comparison doesn't really make much of a sense anyway.
And of course, the compiler doesn't actually do any checks. If I want, I can override the == operator to always return false. Or to only check some ID for equality. Or to change the objects being compared, if you are feeling particularly evil. In the end, it's just a static method like any other (with a few restrictions).
EDIT:
To address your edit directly, string always performs a content comparison because both its == and Equals are overriden to perform a content comparison. However, that doesn't mean that it always performs a costly char-by-char comparison - if you look how string.Equals is actually implemented, you can see that it tries a few things to avoid the costly comparison:
If the string is null, they must be different
If the two strings are reference-equal, they must also be content-equal
If the two strings don't have the same length, they must be different
You can see the actual by-value comparison method here - http://referencesource.microsoft.com/#mscorlib/system/string.cs,11648d2d83718c5e A simple piece of unsafe code, but manually written code nevertheless. There's no automatic value comparison in .NET (though there's tricks that come close).
It's because it makes sense.
Java couldn't do it this way because it doesn't have operator overloading, but that's no argument in C#.
This isn't unique to strings, by the way. Any type could overload the == operator to do something similar.
Any object can override/overload Equals or ==, so they can behave however the library author wants them to behave.
This question already has answers here:
Closed 10 years ago.
The community reviewed whether to reopen this question 11 months ago and left it closed:
Original close reason(s) were not resolved
Possible Duplicate:
C# difference between == and .Equals()
For comparing two variables we can use == or Equals method. for example,
string a = new string(new char[] {'a', 'b', 'c', 'd'});
string b = new string(new char[] {'a', 'b', 'c', 'd'});
Console.WriteLine (a==b);
Console.WriteLine (a.Equals(b));
My question is When should I use == and when should I use Equals? Is there any difference between the two?
== is an operator, which, when not overloaded means "reference equality" for classes (and field-wise equality for structs), but which can be overloaded. A consequence of it being an overload rather than an override is that it is not polymorphic.
Equals is a virtual method; this makes it polymorphic, but means you need to be careful not to call it on null instances.
As a rule of thumb:
if you know the type of something, and know it has an == overload (most core types such as string, int, float, etc have == meanings), then use ==
if you don't know the type, Equals(a,b) may be recommended, as this avoids the null issue
if you really want to check for the same instance (reference equality), consider using ReferenceEquals(a,b), as this will work even if the == is overloaded and Equals overridden
when using generics, consider EqualityComparer<T>.Default.Equals(a,b) which avoids the null issue, supports Nullable-of-T, and supports IEquatable-of-T
This post by John Skeet will answer your question:
So, when should you use which operator? My rule of thumb is that for
almost all reference types, use Equals when you want to test equality
rather than reference identity. The exception is for strings -
comparing strings with == does make things an awful lot simpler and
more readable but you need to remember that both sides of the operator
must be expressions of type string in order to get the comparison to
work properly.
For value types, I'd normally use == for easier-to-read code. Things
would get tricky if a value type provided an overload for == which
acted differently to Equals, but I'd consider such a type very badly
designed to start with.
[Author: Jon Skeet]
http://blogs.msdn.com/b/csharpfaq/archive/2004/03/29/when-should-i-use-and-when-should-i-use-equals.aspx
When == is used on an object type, it'll resolve to
System.Object.ReferenceEquals.
Equals is just a virtual method and behaves as such, so the overridden
version will be used (which, for string type compares the contents).
https://stackoverflow.com/a/814880/655293
string a="I am comparing 2 string";
string b="I am comparing 2 string";
if(a==b)
return true;
else
return false;
How does a .NET compiler compare two strings? Does a string work like a struct(int)?
string is class so a=b means we are comparing 2 object, but i want to compare 2 values.
The String class overloads the == operator, so yes it compares the values of the strings, just like comparing value types like int.
(On a side note, the compiler also interns literal strings in the code, so the string variables a and b will actually be referencing the same string object. If you use Object.ReferenceEquals(a,b) it will also return true.)
System.String is a class which has the == operator overloaded to compare the content of the strings. This allows it to be "value like" in comparison and yet still be a reference type in other respects.
Although string is a reference type, the equality operators (== and !=) are defined to compare the values of string objects, not references. This makes testing for string equality more intuitive.
C# string
Strings are compared by the Runtime, not the compiler. Comparison is performed by Equality operator.
There are different things to keep in mind here.
First, all identical constant strings will be interned so that both references are equal to start with. Therefore, even if you did a ReferenceEquals() here, you'd get "true" as result. So only for a string built (for instance with a StringBuilder, or read from a file etc.) you'd get another reference and therefore false when doing a reference equality comparison.
If both objects are known to be strings at compile time, the compiler will emit code to compare their value (== overloaded operator on System.String), not their references. Note that as soon as you compare it against an object type reference, this isn't the case anymore.
No runtime check is done to compare a string by value, and the compiler does not emit a .Equals() call for the == operator.
Notice that your question is a little tricky. Because ReferenceEquals will ALSO return true.
This is because of Interning : http://en.wikipedia.org/wiki/String_interning
This question already has answers here:
C# difference between == and Equals()
(20 answers)
Closed 9 years ago.
What is the difference between a.Equals(b) and a == b for value types, reference types, and strings? It would seem as though a == b works just fine for strings, but I'm trying to be sure to use good coding practices.
From When should I use Equals and when should I use ==:
The Equals method is just a virtual
one defined in System.Object, and
overridden by whichever classes choose
to do so. The == operator is an
operator which can be overloaded by
classes, but which usually has
identity behaviour.
For reference types where == has not
been overloaded, it compares whether
two references refer to the same
object - which is exactly what the
implementation of Equals does in
System.Object.
Value types do not provide an overload
for == by default. However, most of
the value types provided by the
framework provide their own overload.
The default implementation of Equals
for a value type is provided by
ValueType, and uses reflection to make
the comparison, which makes it
significantly slower than a
type-specific implementation normally
would be. This implementation also
calls Equals on pairs of references
within the two values being compared.
using System;
public class Test
{
static void Main()
{
// Create two equal but distinct strings
string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});
Console.WriteLine (a==b);
Console.WriteLine (a.Equals(b));
// Now let's see what happens with the same tests but
// with variables of type object
object c = a;
object d = b;
Console.WriteLine (c==d);
Console.WriteLine (c.Equals(d));
}
}
The result of this short sample program is
True
True
False
True
Here is a great blog post about WHY the implementations are different.
Essentially == is going to be bound at compile time using the types of the variables and .Equals is going to be dynamically bound at runtime.
In the most shorthand answer:
== opertator is to check identity. (i.e: a==b are these two are the same object?)
.Equals() is to check value. (i.e: a.Equals(b) are both holding identical values?)
With one exception:
For string and predefined value types (such as int, float etc..),
the operator == will answer for value and not identity. (same as using .Equals())
One significant difference between them is that == is a static binary operator that works on two instances of a type whereas Equals is an instance method. The reason this matters is that you can do this:
Foo foo = new Foo()
Foo foo2 = null;
foo2 == foo;
But you cannot do this without throwing a NullReferenceException:
Foo foo = new Foo()
Foo foo2 = null;
foo2.Equals(foo);
At a simple level, the difference is which method is called. The == method will attempt ot bind to operator== if defined for the types in question. If no == is found for value types it will do a value comparison and for reference types it will do a reference comparison. A .Equals call will do a virtual dispatch on the .Equals method.
As to what the particular methods do, it's all in the code. Users can define / override these methods and do anything they please. Ideally this methods should be equivalent (sorry for the pun) and have the same output but it is not always the case.
One simple way to help remember the difference is that a.Equals(b) is more analogous to
a == (object)b.
The .Equals() method is not generic and accepts an argument of type "object", and so when comparing to the == operator you have to think about it as if the right-hand operand were cast to object first.
One implication is that a.Equals(b) will nearly always return some value for a and b, regardless of type (the normal way to overload is to just return false if b is an unkown type). a == b will just throw an exception if there's no comparison available for those types.
"==" is an operator that can be overloaded to perform different things based on the types being compared.
The default operation performed by "==" is a.Equals(b);
Here's how you could overload this operator for string types:
public static bool operator == (string str1, string str2)
{
return (str1.Length == str2.Length;)
}
Note that this is different than str1.Equals(str2);
Derived classes can also override and redefine Equals().
As far as "best practices" go, it depends on your intent.
For strings you want to be careful of culture specific comparisons. The classic example is the german double S, that looks a bit like a b. This should match with "ss" but doesn't in a simple == comparison.
For string comparisons that are culture sensitive use: String.Compare(expected, value, StringComparison....) == 0 ? with the StringComparison overload you need.
By default, both == and .Equals() are equivalent apart from the possibility of calling .Equals() on a null instance (which would give you a NullReferenceException). You can, however, override the functionality of either of them independently (though I'm not sure that would ever be a good idea unless you're trying to work around the shortcomings of another system), which would mean you could MAKE them different.
You'll find people on both sides of the aisle as to the one to use. I prefer the operator rather than the function.
If you're talking about strings, though, it's likely a better idea to use string.Compare() instead of either one of those options.