Created
May 5, 2014 18:13
-
-
Save forcewake/52ec98f304293c1d37b2 to your computer and use it in GitHub Desktop.
Safe compare null-string
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NullSafeStringComparer : StringComparer | |
{ | |
private readonly StringComparer baseStringComparer; | |
public static NullSafeStringComparer NullSafeInvariantCulture | |
{ | |
get | |
{ | |
return new NullSafeStringComparer(InvariantCulture); | |
} | |
} | |
public static StringComparer NullSafeInvariantCultureIgnoreCase | |
{ | |
get | |
{ | |
return new NullSafeStringComparer(InvariantCultureIgnoreCase); | |
} | |
} | |
public static StringComparer NullSafeOrdinal | |
{ | |
get | |
{ | |
return new NullSafeStringComparer(Ordinal); | |
} | |
} | |
public static StringComparer NullSafeOrdinalIgnoreCase | |
{ | |
get | |
{ | |
return new NullSafeStringComparer(OrdinalIgnoreCase); | |
} | |
} | |
private NullSafeStringComparer(StringComparer baseStringComparer) | |
{ | |
this.baseStringComparer = baseStringComparer; | |
} | |
public override int Compare(string x, string y) | |
{ | |
try | |
{ | |
return baseStringComparer.Compare(x, y); | |
} | |
catch (Exception exception) | |
{ | |
return 0; | |
} | |
} | |
public override bool Equals(string x, string y) | |
{ | |
try | |
{ | |
return baseStringComparer.Equals(x, y); | |
} | |
catch (Exception e) | |
{ | |
return false; | |
} | |
} | |
public override int GetHashCode(string obj) | |
{ | |
try | |
{ | |
return this.baseStringComparer.GetHashCode(obj); | |
} | |
catch (Exception exception) | |
{ | |
return 0; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment