Quick Tip: Comparing a .NET string to multiple values

The Problem

Do you ever wish you could use the SQL IN operator in your C# code to make your conditional blocks more concise and your code easier to read?

Perhaps it’s just my persnickety nature, but I believe that line-wrapped conditional expressions like this are a code smell.

if (animal.Equals("Cow") ||   animal.Equals("Horse") ||   animal.Equals("Hen")){   Console.WriteLine("We must be on the farm.");}

This would be so much cleaner…

if (animal.CompareMultiple("Cow","Horse","Hen"){   Console.WriteLine("We must be on the farm.");}

The Code

With a simple extension class you can upgrade your string classes to do this very thing.

Step 1: Create an extension class as demonstrated here.


namespace extenders.strings{  public static class StringExtender {    public static bool CompareMultiple(this string data, StringComparison compareType, params string[] compareValues) {      foreach (string s in compareValues) {        if (data.Equals(s, compareType)) {          return true;        }      }      return false;   }  }}


Imports System.Runtime.CompilerServicesNamespace Extenders.Strings  Public Module StringExtender    <Extension()> _    Public Function CompareMultiple(ByVal this As String, compareType As StringComparison, ParamArray compareValues As String()) As Boolean       Dim s As String       For Each s In compareValues         If (this.Equals(s, compareType)) Then            Return True         End If       Next s       Return False    End Function  End ModuleEnd Namespace

Step 2: Add a reference to the extension namespace and use it.


using extenders.strings;namespace MyProgram{  static class program {    static void Main() {      string foodItem = "Bacon";      if (foodItem.CompareMultiple(StringComparison.CurrentCultureIgnoreCase, "bacon", "eggs", "biscuit")) {         System.Console.WriteLine("Breakfast!");      }      else {         System.Console.Write("Dinner");      }    }  }}


Imports StringExtenderExampleVB.Extenders.StringsModule Program  Sub Main()    Dim foodItem As String = "Bacon"    If (foodItem.CompareMultiple(System.StringComparison.CurrentCultureIgnoreCase, "bacon", "eggs", "biscuit")) Then      System.Console.WriteLine("Breakfast!")    Else      System.Console.Write("Dinner")    End If    System.Console.ReadLine()  End SubEnd Module

Leave a Reply

Your email address will not be published. Required fields are marked *