0

I've found a topic in Here which is about how you could create a drop-down list from an enum in MVC. Here's the answer in that topic:

Martin Faartoft says:

I rolled Rune's answer into an extension method:

public static SelectList ToSelectList<TEnum>(this TEnum enumObj)
{
  var values = from TEnum e in Enum.GetValues(typeof(TEnum))
               select new { Id = e, Name = e.ToString() };

  return new SelectList(values, "Id", "Name", enumObj);
}

I exactly need to do this but it uses extension methods which I have no idea what it is and how I could implement it. so can anyone help me get this piece of code working ? I need to know what are extension methods and how I could implement them.

thanks

Community
  • 1
  • 1
Ali
  • 1,152
  • 2
  • 14
  • 33
  • 2
    Have you tried looking at the MSDN documentation for extension methods? http://msdn.microsoft.com/en-us/library/bb383977.aspx – Manatherin Aug 23 '12 at 09:53

1 Answers1

1

Extension methods are members of static classes that have one or more parameters, the first one of which must be attributed with the this keyword as in your code sample.

From then on, you can use the extension method on any instance of the given type, as long as the namespace that contains the class is added as a using statement.

Sample for a class holding an extension method:

public static class ExtensionMethods
{
    public static string Reverse(this string source)
    {
        string result = String.Empty;
        for (int i = 0; i < source.Length; i++)
            result = source.Substring(i, 1) + result;

        return result;
    }
}

Use this extension method like

string toBeReversed = "Hello World";
string reversed = toBeReversed.Reverse();

The whole point is to add functionality to existing types without actually inheriting from it. Using extension methods, you can "attach" new functionality to any given type without actually changing it.

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
  • 1
    My comment is not about extension method, but about Reverse function. Never do such function through string. Use StringBuilder against string inside cycle. – Kirill Bestemyanov Aug 23 '12 at 10:03
  • @KirillBestemyanov: I know :-) Normally I'd to that, too, but as it was just for the sake of demonstration I thought it might be ok. – Thorsten Dittmar Aug 23 '12 at 10:11
  • It worked ;) I kinda figured how it works :D Thanks Thorsten Dittmar ! – Ali Aug 23 '12 at 10:24