tags:

views:

84

answers:

4

Take this enum for example:

public enum PersonName : short
{
    Mike = 1,
    Robert= 2
}

I wnat to have en extension method like this:

PersonName person = PersonName.Robert;
short personId = person.GetId();
//Instead of:
short personId = (short)person;

Any idea how to implement this?

it need to be generic to int, short etc..., and to generic enums as well, not limited to PersonName.

A: 

I believe you should be able to define an extension mehtod on the PersonName class:

public static class PersonExtensions // now that sounds weird...
{
    public static short GetID (this PersonName name)
    {
        return (short) name;
    }
}

Side node: I somehow hope that the code in your question is overly simplified, as it does not seem quite right to implement a person repository as an enum :)

Jørn Schou-Rode
I want it to be a generic. and of course this was an example :)
Mendy
Sorry, didn't catch that in your question. I am afraid I am not sure what you mean by "generic" in this context, but it seems like others have figured it out :)
Jørn Schou-Rode
A: 

Is there any reason you can't turn it into a class? It would probably make more sense in context of a class.

Zach Johnson
Good point. And how get the person-property name, using reflation? or each one should return dictionary? I'll think about it. bu the question still interesting to me.
Mendy
A: 

I would just use something like IEnumerable<KeyValuePair<string,short>> or Dictionary<string,short>... you can add your extensions to IDictionary or IEnumerable if you want.

Perpetualcoder
That what I'm going to use by now. But about the question, this behavior I wanted a lot of time, but from my knowledge it not possible to achieve.
Mendy
+1  A: 

This is completely impossible.

You cannot constrain a method based on an enum's underlying type.

Explanation:

Here is how you might try to do this:

public static TNumber GetId<TEnum, TNumber>(this TEnum val) 
       where TEnum : Enum 
       where TEnum based on TNumber

The first constraint is unfortunately not allowed by C#, and the second constraint is not supported by the CLR.

SLaks
I think you're right. You have an explanation *why*?
Mendy
You can "sort of" (well, you create the effect) - http://msmvps.com/blogs/jon_skeet/archive/2009/09/10/generic-constraints-for-enums-and-delegates.aspx
adrianbanks
See also: http://stackoverflow.com/questions/7244/anyone-know-a-good-workaround-for-the-lack-of-an-enum-generic-constraint
Jørn Schou-Rode