I have the following C# code (from a library I'm using) that tries to find a certificate comparing the thumbprint. Notice that in the following code both mycert.Thumbprint
and certificateThumbprint
are strings.
var certificateThumbprint = AppSettings.CertificateThumbprint; var cert = myStore.Certificates.OfType<X509Certificate2>().FirstOrDefault( mycert => mycert.Thumbprint != null && mycert.Thumbprint.Equals(certificateThumbprint) );
This fails to find the certificate with the thumbprint because mycert.Thumbprint.Equals(certificateThumbprint)
is false
even when the strings are equal. mycert.Thumbprint == certificateThumbprint
also returns false
, while mycert.Thumbprint.CompareTo(certificateThumbprint)
returns 0.
I might be missing something obvious, but I can't figure out why the Equals
method is failing. Ideas?
By default, the equals() method returns false if the two objects aren't the same instance... This may seem obvious but sometimes the default behavior is not what you want... Now the equals() method will return true if two instances of Payment have the same currency and value.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
This is because the two Integer objects have the same value, but they are not the same object.
The equals() method compares two strings, and returns true if the strings are equal, and false if not. Tip: Use the compareTo() method to compare two strings lexicographically.
CompareTo ignores certain characters:
static void Main(string[] args) { var a = "asdas"+(char)847;//add a hidden character var b = "asdas"; Console.WriteLine(a.Equals(b)); //false Console.WriteLine(a.CompareTo(b)); //0 Console.WriteLine(a.Length); //6 Console.WriteLine(b.Length); //5 //watch window shows both a and b as "asdas" }
(Here, the character added to a
is U+034F
, Combining Grapheme Joiner.)
So CompareTo's result is not a good indicator of a bug in Equals. The most likely reason of your problem is hidden characters. You can check the lengths to be sure.
See this for more info.
You may wish to try using an overload of String.Equals
that accepts a parameter of type StringComparison
.
For example:
myCert.Thumbprint.Equals(certificateThumbprint, StringComparison.[SomeEnumeration])
Where [SomeEnumeration]
is replaced with one of the following enumerated constants:
- CurrentCulture - CurrentCultureIgnoreCase - InvariantCulture - InvariantCultureIgnoreCase - Ordinal - OrdinalIgnoreCase
Reference the MSDN Documentation found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With