Tuesday, November 11, 2014

Extension Methods C# Asp.net

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. So it’s static method and declares in static class. The declaration between a regular method and an extension method is the "this" keyword in the parameter list.  Here is the example of extension method in c# is given below
So first I have created static class and create method “CommaSplitedValues
public static class Extension
{
    public static  String[] CommaSplitedValues(this string str)
    {

        string[] values = str.Split(',');
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = values[i].Trim();
        }
        return values;
    }
   
}

How to call this method in controller
  public ActionResult CategoriesList(string CategoryName)
        {

            string EmployeeIds = "1,3,4,5,6,8";
            var items = EmployeeIds.CommaSplitedValues();

          
            return View();
        }

No comments:

Post a Comment

http://blogsiteslist.com