Pages

Thursday, September 29, 2011

IsIn extension method

My motivation for writing blogs is to share my knowledge, although I am not a so professional developer. With the advent of extension methods I find it very helpful and started to use them everyday. Now I am going to share some of those small extension methods that may help you in writing your codes, maybe simply to make your codes pretty looking.

Name
IsIn
Purpose
Lots of the time we use expressions like this:

if (x = value1 || x = value2 || x = value3 || x = value4 || x = value5) {
 
}

The problem with these codes are:
It's very dirty code and hard to understand, specially if the variables names and values are too long. which sometimes are.
If the if block contains other conditions it's bug prone to edit condition operators and if by mistake you change an or (||) operator with an and(&&) operator, you can't find the bug easily.
Extension Method
The code for extension method is very simple and straight. Most of the time extension methods that I wrote is just  a reversed version of another metohd which here the IsIn extension method simply call the Any method on the list of possible  values:
public static bool IsIn<T>(this T source, params T[] list)
{
    Func<T, T, bool> compare = (v1, v2) => EqualityComparer<T>.Default.Equals(v1, v2);
    return list.Any(item => compare(item, source));
}

Usage
Now you can easily use it very simple:
Before code:
if (x == 1 || x == 2 || x == 7 || x == 8)
    Console.WriteLine("X is a magic number");
After code:
if (x.IsIn(1 , 2 , 7 , 8))
    Console.WriteLine("X is a magic number");

Whole thing
If you just need to copy, this is the block of code you need to copy and paste in your class library and then you just need to correct the namespace with your own naming conventions:
using System;
using System.Collections.Generic;
using System.Linq;
 
namespace MyApp.Common
{
    public static class ExtensionMethods
    {
        public static bool IsIn<T>(this T source , params T[] list)
        {
            Func<T, T, bool> compare = (v1 , v2) => EqualityComparer<T>.Default.Equals(v1 , v2);
            return list.Any(item => compare(item , source));
        }
    }
}