Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overwrite the == operator globally

In a lot of places I'm using the == operator to compare the string, now I know this considers casing... Is there anyway I can adjust the culture settings to avoid this or do I have to go to every line of code and change it to

string.Compare(a,b,StringComparison.CurrentCultureIgnoreCase)
like image 546
user1106741 Avatar asked Jun 08 '26 13:06

user1106741


1 Answers

How about a string extension method?:

public static class StringExtensions {
    public static bool EqualsIC(this string self, string string1) {
        return self.Equals(string1, StringComparison.InvariantCultureIgnoreCase);        
    }
}

Then you can just use

string string1 = "Hello world";
string string2 = "hEllO WOrLD";
bool theymatch = string1.EqualsIC(string2);

// OR (per TimS' comment) - to avoid error if string1 is null
theymatch = StringExtensions.EqualsIC(string1, string2);

As an esoteric alternative, you could use Regex instead of String.Compare:

public static bool EqualsICRX(this string self, string string1) {
    return Regex.IsMatch(string1, "^" + self + "$", RegexOptions.IgnoreCase);
}
like image 78
Joshua Honig Avatar answered Jun 11 '26 03:06

Joshua Honig