-1

I was about to write a method that has to decide whether or not to ignore case while comparing two strings.

public bool IsCaseSensitiveUsing(StringComparison comparer)
{
    if (comparer == StringComparison.CurrentCulture | 
        comparer == StringComparison.InvariantCulture | 
        comparer == StringComparison.Ordinal))
            return true;

    return false;

 }

Is there a better way to do it?

Mhd
  • 2,778
  • 5
  • 22
  • 59
  • what about just `StringComparison.OrdinalIgnoreCase`? – Rahul Jul 01 '17 at 20:35
  • The method will not reflect the real parameter. `OrdinalIgnoreCase` is the same as `CurrentCultureIgnoreCase` and `InvariantCulture.IgnoreCase` ? – Mhd Jul 01 '17 at 20:41
  • 1
    Define "better"? You can do `return (int)comparer % 2 != 0` or `return !comparer.ToString().EndsWith("IgnoreCase")`, It's shorter, but I wouldn't call that better – Kevin Gosse Jul 01 '17 at 20:43
  • @KevinGosse "better" means shorter. I like `(int)comparer % 2 != 0` idea. But why is not better? – Mhd Jul 01 '17 at 20:48
  • Because while shorter, it's much less readable – Kevin Gosse Jul 01 '17 at 20:50
  • Side note: StringComparison.CurrentCulture is not "case sensitive" or "case insensitive" - so you code is not exactly correct... Whether you care or not is different question - it does not impact answers of "how to check if enum value belongs to as set" like - https://stackoverflow.com/questions/7477692/c-best-way-to-check-against-a-set-of-enum-values – Alexei Levenkov Jul 01 '17 at 21:46

2 Answers2

0

I suggest implementng extension method:

   public static class StringComparisonExtensions {
     public static bool IsCaseSensitiveUsing(this StringComparison value) {
       return (value == StringComparison.CurrentCulture || 
               value == StringComparison.InvariantCulture || 
               value == StringComparison.Ordinal); 
     }
   } 

   ....

   StringComparison myComparison = ...

   // Check as if StringComparison has IsCaseSensitiveUsing method:
   if (myComparison.IsCaseSensitiveUsing()) {
     ...
   }
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

You can make a set of StringComparison values that require case sensitivity, and use it in your method:

private static readonly ISet<StringComparison> caseSensitive = new HashSet<StringComparison> {
    StringComparison.CurrentCulture
,   StringComparison.InvariantCulture
,   StringComparison.Ordinal
};
public static bool IsCaseSensitiveUsing(StringComparison comparer) {
    return caseSensitive.Contains(comparer);
}
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523