Extension Method on Enumeration, Not Instance of Enumeration

Extension method on enumeration, not instance of enumeration

Extension methods only work on instances, so it can't be done, but with some well-chosen class/method names and generics, you can produce a result that looks just as good:

public class SelectList
{
// Normal SelectList properties/methods go here

public static SelectList Of<T>()
{
Type t = typeof(T);
if (t.IsEnum)
{
var values = from Enum e in Enum.GetValues(type)
select new { ID = e, Name = e.ToString() };
return new SelectList(values, "Id", "Name");
}
return null;
}
}

Then you can get your select list like this:

var list = SelectList.Of<Things>();

IMO this reads a lot better than Things.ToSelectList().

Enumeration extension methods

Yes, just code against the base Enum type, e.g.

public static void Something(this Enum e)
{
// code here
}

The down-side is you'll probably end up doing some quite nasty stuff like finding the real base type using Enum.GetUnderlyingType, casting, and going down different branches depending on what the base type of the enum is, but you can find some good uses for it (e.g. we have IsOneOf and IsCombinationOf methods that apply to all enums).

PS: Remember when writing the method that, although ill advised, you can use float and double as the base types for enums so you'll need some special cases for those as well as unsigned values.

Possible to use extensions methods on a generic Enum Type? (not enum value)

No, you cannot do that, not as long as TestEnum is an enum type, as you cannot extend these with members.

Since TestEnum is not an instance, and you can only create extension methods for instances, not for types, you cannot get TestEnum.ToSequence() to compile.

So the best you can get is to call the method manually, and not as an extension method.

Now, as @Bagdan Gilevich mentions in his comment, this should compile:

TestEnum.SomeEnumItem.ToSequence()

I'll leave opinions aside, you will have to make up your own mind if this is acceptable.

There is also a language feature suggestion for C# 8 (or later), called Extension Everything. This may give you what you want but we'll have to see what happens with it.

Count and ToList extension method for Enum?

You can use e.GetType() instead of typeof(???)

public static int Count(this Enum e) 
{
return Enum.GetNames(e.GetType()).Length;
}

however, I don't think it will work as you expect as you cannot do this:

var shouldBe7 = DayOfWeek.Count(); // does not compile

but you can do

var shouldBe7 = DayOfWeek.Monday.Count(); // 7

It may be better to simply do:

public static class EnumHelper
{
public static int Count(Type e)
{
// use reflection to check that e is an enum
// or just wait for the Enum method to fail

return Enum.GetNames(e).Length;
}
}

which is then used as

var shouldBe7 = EnumHelper.Count(typeof(DayOfWeek)); // 7

How to add extension methods to Enums

According to this site:

Extension methods provide a way to write methods for existing classes in a way other people on your team might actually discover and use. Given that enums are classes like any other it shouldn’t be too surprising that you can extend them, like:

enum Duration { Day, Week, Month };

static class DurationExtensions
{
public static DateTime From(this Duration duration, DateTime dateTime)
{
switch (duration)
{
case Day: return dateTime.AddDays(1);
case Week: return dateTime.AddDays(7);
case Month: return dateTime.AddMonths(1);
default: throw new ArgumentOutOfRangeException("duration");
}
}
}

I think enums are not the best choice in general but at least this lets you centralize some of the switch/if handling and abstract them away a bit until you can do something better. Remember to check the values are in range too.

You can read more here at Microsft MSDN.

Enum Extension Method is not showing

Extension methods can be applied on instances only

public static class EnumExtensions {
// This extension method requires "value" argument
// that should be an instance of Enum class
public static string GetDescriptionAttr(this Enum value, string key) {
...
}
}

...

public enum MyEnum {
One,
Two,
Three
}

Enum myEnum = MyEnum.One;

// You can call extension method on instance (myEnum) only
myEnum.GetDescriptionAttr("One");

How to create extension method for Enum type argument?

In general your problem is connected with the fact that you want to create a generic extensions method (that's possible) but without any object reference sent as "this" parameter when calling such a method (that's not possible).
So using extension methods is not an option to achieve what you want.

You could do sth like this:

public static Dictionary<string, string> EnumToDictionary(this Enum @enum)
{
var type = @enum.GetType();
return Enum.GetValues(type).Cast<string>().ToDictionary(e => e, e => Enum.GetName(type, e));
}

But this would mean that you need to operate on a certain instance of enum class to call such an extension method.

Or you could do this in such a way:

    public static IDictionary<string, string> EnumToDictionary(this Type t)
{
if (t == null) throw new NullReferenceException();
if (!t.IsEnum) throw new InvalidCastException("object is not an Enumeration");

string[] names = Enum.GetNames(t);
Array values = Enum.GetValues(t);

return (from i in Enumerable.Range(0, names.Length)
select new { Key = names[i], Value = (int)values.GetValue(i) })
.ToDictionary(k => k.Key, k => k.Value.ToString());
}

And then call it like this:

var result = typeof(MyEnum).EnumToDictionary();

C# extend method for Enum object

This has nothing to do with Enum as such - but extension methods "look" like they're instance methods. You can't "pretend" to add static methods, as it looks like you're currently trying to do.

You would be able to do:

Pets.SomeValue.something()

... because that's calling the extension method on an "instance" (a value). It will end up boxing the value, mind you.



Related Topics



Leave a reply



Submit