had an argument with someone on how to compare string values in c# and i want to get some opinions which option is better and why:
== or string.Equals(string) ?
had an argument with someone on how to compare string values in c# and i want to get some opinions which option is better and why:
== or string.Equals(string) ?
== is better because it's more concise. functionally they're the same
ok but i still don't get why the docs are suggesting "Equals" then
One compare references, other values.
that's what the whole argument was about, because in the case of strings Equals actually compares values
== is more concise but is only overloaded where it makes sensen(datetime, string)
You have to follow this:
>msdn.microsoft.com
Equals check for full equality and == check for reference equality is the general case.
The same way == can be abused can be applied to the implementation of equals
which docs? have you tried asking stackexchange?
docs.microsoft.com
this guide suggests using equals
>When you test for equality of strings, you should use the methods that explicitly specify what kind of comparison you intend to perform. It makes your code is much more maintainable and readable.
This is true for all production code that deal with diferent languages and encodings.
== is the simplest form when you want to compare in-program strings and hardcoded settings.
Equals allows for setting the comparison method and is good practise but it might throw an exception if used on a null object hence one must take care of that when using it.
Java doesn't have this problem.