Friday 28 August 2009

Some Useful Extension Methods

In
Syntax:

public static bool In(this T e, params T[] list)
{
return list.Any(l => e.Equals(l));
}

Example:

var array = new [] {1,2,3,4};
var index = 1;
if (index.In(array))
// do some action

ToEnum
Syntax:
public static T ToEnum(this string value)
{
return (T)Enum.Parse(typeof(T), value);
}

Example:
public enum SessionKey
{
IsLoggedIn, ReportId
}
//---------------
var myString = "ReportId";
switch (myString.ToEnum())
{
case SessionKey.ReportId:
// do some action
case SessionKey.IsloggedIn:
// do some action
}

More to learn:

No comments: