Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String comparison equivalents

I believe these 2 lines are equivalent but after running into a strange issue I no longer believe this to be the case.

String mimeType = context.Request.ContentType;
(String.Compare("text/xml", mimeType, true) == 0))

is the same as :

context.Request.ContentType.ToLower().Equals("text/xml")

Are their implementations in the CLR any different?

like image 334
tgandrews Avatar asked Sep 15 '26 12:09

tgandrews


2 Answers

They are not equivalent, and ToLower/ToUpper may have some localization issues. The way to compare two strings without case-sensitivity (considering one of the strings may be null, which is why I don't like the str1.Equals method) is the static String.Equals method:

bool areEqual = String.Equals(str1, str2, StringComparison.OrdinalIgnoreCase);
like image 155
mkedobbs Avatar answered Sep 17 '26 02:09

mkedobbs


They are not completely equivalent; see here.

Here is the correct way to do a case insensitive comparison:

bool areSame = str1.Equals(str2, StringComparison.OrdinalIgnoreCase);

This way will also be more efficient becasue it doesn't allocate a separate string for the lowercase copy.

like image 44
SLaks Avatar answered Sep 17 '26 00:09

SLaks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!