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.
C#
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; } } }
VB.NET
Imports System.Runtime.CompilerServices Namespace 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 Module End Namespace
Step 2: Add a reference to the extension namespace and use it.
C#
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"); } } } }
VB.NET
Imports StringExtenderExampleVB.Extenders.Strings Module 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 Sub End Module
Filed under: Useful Code Snippets | Tagged: c#, Code, Extenders, Strings, tips, vb.net | 2 Comments »