0

Lets say I got the extension which does something with the enum and then just returns it.

public static T Do<T>(this Enum e) where T : struct
{
    // Do something.
    return // e? .. (T)e? .. or (T)(object)e? ;
}

So what should I return to let my code be successefully built and run with this example:

Roles role = Roles.Admin | Roles.Moderator;
role.Do<Roles>().SomethingElse().AndMore<Roles>().Etc<int>();

__

return (T)e;

http://pasteboard.s3.amazonaws.com/images/1349685696025173.png

__

return e;

http://pasteboard.s3.amazonaws.com/images/1349685753912110.png

__

return (T)(object)e;

Actually works, but does boxing and then unboxing.

AgentFire
  • 8,944
  • 8
  • 43
  • 90
  • What is your specific problem? Adding more extension methods should not be the problem. – Felix K. Oct 08 '12 at 08:40
  • How is the `SomethingElse` method defined? What type does it expect to operate upon? – Darin Dimitrov Oct 08 '12 at 08:44
  • @DarinDimitrov that's not the point. The point is in the `Do` method. – AgentFire Oct 08 '12 at 08:44
  • @AgentFire, of course that it is the point. You have to return the type that the next function in the chain expects. – Darin Dimitrov Oct 08 '12 at 08:45
  • @DarinDimitrov I have to return the type I have received as an input. So I am asking the best way to do that. – AgentFire Oct 08 '12 at 08:45
  • 1
    @AgentFire Then remove the generic parameter and return the enum type.... – Felix K. Oct 08 '12 at 08:47
  • 1
    @AgentFire Just as a note, the `Enum` *class* will cause boxing of arguments in your sample above. There isn't an easy way to get constraints on `enum` types, but [Jon Skeet has some code exploring the area](http://code.google.com/p/unconstrained-melody/). – Adam Houldsworth Oct 08 '12 at 08:47
  • @FelixK. in that case I will lose the desirable return type (`Roles` or whatever). – AgentFire Oct 08 '12 at 08:49
  • 1
    Just for your information: http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum – sloth Oct 08 '12 at 08:52

3 Answers3

1
    public static T Do<T>(this Enum e) where T : struct
    {
        return (T) Convert.ChangeType(e, typeof(T));
    }
Dmitrii Dovgopolyi
  • 6,231
  • 2
  • 27
  • 44
1

This is a tricky one due to the fact that you can't place an Enum constraint on a generic.

Have a look at this article for more, and a possible workaround:

http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx

Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
0

Well you have to obey the mathematical construct of Closure.
Wikipedia explaines this well: Closrue

In a short sentence:
In your case you have to return what your next functions exprects as input parameter.

TGlatzer
  • 5,815
  • 2
  • 25
  • 46