Extensions Method in .NET


Recently I use extension method in C# project. I knew those for years, but really never get a chance to use them where they are most effect. I have couple of extension method in my project, such as ToInteger(), for a string to convert a String to Integer, which I used more frequently in my project. But that doesn’t seems a good use of technology to me.

But I now found a perfect use for extension method. i.e. I was upgrade my code from old ASP.NET project to MVC and for this I am making a class library of all objects. Now, this scenario need me to make a conversion from old enum to new enum  which are now part of namespace of my class library, rather than sitting around in App_Code folder. Here I make a extension method that convert a OLD enum to new name space base. This ease lot of my works.

Method goes like:


public static NewType GetSaleType(this OldType s)
{
	NewType r = NewType.Regular;
	switch (s)
	{
		case OldType.BK: r = NewType.BK; break;
		case OldType.IL: r = NewType.IL; break;
		case OldType.MM: r = NewType.MM; break;
		case OldType.PC: r = NewType.PC;break;
		case OldType.Regular: r = NewType.Regular; break;
		case OldType.Trigger:r = NewType.Trigger; break;
	}
	return r;
}
, ,