Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
179 views
in Technique[技术] by (71.8m points)

c# - Why String.Equals is returning false?

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.

enter image description here

I might be missing something obvious, but I can't figure out why the Equals method is failing. Ideas?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Debug mode

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...