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
Extension methods are members of
staticclasses that have one or more parameters, the first one of which must be attributed with thethiskeyword 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
usingstatement.Sample for a class holding an extension method:
Use this extension method like
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.