Caveman's Blog

My commitment to learning.

Posts Tagged ‘C# 3.x

C# 3.0: Extension method “In”

leave a comment »


Extension methods allows existing classes to be extended with out having to change the class’s source code. This means that we can add new functionality to existing like the String class, where we do not have access to modifying the source code. Here is one such extension method for the String class. Note that the class is defined as non-generic static and the “this” keyword specifies the type on which extension method is a part of.

The “In” extension method can be used to check if a given string exists in a set of strings.

public static class Extensions
{
      public static bool In(this string t, params string[] values)
      { return values.Contains(t); }
}

Usage: In the code below an we are trying to check if an input string “new” exists in a give list of strings (“new”,  “renew”) and it can be called in an application by this syntax

string[] strList = { "new", "renew" };
string inputStr = "new";
if (inputStr.In(strList))
    Console.WriteLine("Found a match");

References:
1. Extension Methods (C# Programming Guide)

Written by cavemansblog

March 8, 2012 at 6:25 pm