Elegant way of converting between StringComparison and StringComparer?

Some .NET methods use StringComparison as parameter, some use StringComparer (often in form of IComparer). The difference is clear. Is there some elegant way how to get StringComparison from StringComparer or vice versa?

I can always write simple method which uses Case statement, but perhaps there is already something present in .NET what I am overlooking.

Jon Skeet
people
quotationmark

Going from StringComparison to StringComparer is simple - just create a Dictionary<StringComparison, StringComparer>:

var map = new Dictionary<StringComparison, StringComparer>
{
    { StringComparison.Ordinal, StringComparer.Ordinal },
    // etc
};

There is a StringComparer for every StringComparison value, so that way works really easily. Mind you, StringComparer.CurrentCulture depends on the current thread culture - so if you populate the dictionary and then modify the thread's culture (or do it from a different thread with a different culture) you may end up with the wrong value. You potentially want a Dictionary<StringComparison, Func<StringComparer>>:

var map = new Dictionary<StringComparison, Func<StringComparer>>
{
    { StringComparison.Ordinal, () => StringComparer.Ordinal },
    // etc
};

Then you can get a comparer at any time by invoking the delegate:

var comparer = map[comparison]();

Going the other way is infeasible, because not every StringComparer has a suitable StringComparison. For example, suppose I (in the UK) create a StringComparer for French (StringComparer.Create(new CultureInfo(..., true)). Which StringComparison does that represent? It's not correct for the current culture, the invariant culture, or ordinal comparisons.

people

See more on this question at Stackoverflow