Caveman's Blog

My commitment to learning.

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");

1. Extension Methods (C# Programming Guide)

Written by cavemansblog

March 8, 2012 at 6:25 pm

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: