The scenario:
We have on our .Net Core 3.1 application many file paths (of windows OS) that we need to compare and store in Hashsets and Dictionaries that use string comparison (case insensitive).
I tried to find an easy way to handle all these file paths strings and I found 3 options:
Option 1:
Use StringComparison.OrdinalIgnoreCase
and use StringComparer.OrdinalIgnoreCase
.
- Advantage: No need to implement a new class, just use the existing framework.
- Big Disadvantage: Very easy to forget these while developing new code. (We have many strings in the application that are not case insensitive)
Option 2:
Create a IgnoreCaseString
class that wraps the string
class and overrides Equals
, GetHashCode
and operator ==
with StringComparison.OrdinalIgnoreCase
.
public sealed class IgnoreCaseString
{
public IgnoreCaseString(string originalString)
{
this.OriginalString = originalString;
}
public string OriginalString { get; }
public override bool Equals(object obj)
{
if (ReferenceEquals(this, obj))
return true;
if (!(obj is IgnoreCaseString filePathString))
return false;
return OriginalString.Equals(filePathString.OriginalString, StringComparison.OrdinalIgnoreCase);
}
public static bool operator ==(IgnoreCaseString a, IgnoreCaseString b)
{
return Equals(a, b);
}
public static bool operator !=(IgnoreCaseString a, IgnoreCaseString b)
{
return !Equals(a, b);
}
public override int GetHashCode()
{
return OriginalString.GetHashCode(StringComparison.OrdinalIgnoreCase);
}
}
- Advantage: Very optimize, use the existing string methods, and easy to use.
- Disadvantage: Need to maintain the
IgnoreCaseString
class.
Option 3:
Use Uri
class which is designated for it.
- Advantage: Existing class, easy to use.
- Disadvantage: Memory and performance overhead.
The question:
- Is there any built-in or easy way to do it?
- Is there another option that I miss?