Reputation: 2012
I'm trying to add static methods to a C# enum. By adding a static class
, I can create a 'getter' method, which converts the enum value in e.g. a byte. However, I cannot seem to make a 'construction' method, which takes the byte and converts it into an enum. In java, I would use the below code without the separate static class.
Enum code:
public enum PoseLocation {
UP,
DOWN,
LEFT,
RIGHT,
UP_LEFT,
UP_RIGHT,
DOWN_LEFT,
DOWN_RIGHT
}
public static class PoseLocationMethods {
public static byte toByte (this PoseLocation location) {
return (byte)location;
}
public static PoseLocation fromByte (byte poseByte) {
return (PoseLocation)poseByte;
}
}
Method calls:
byte poseByte = PoseLocation.UP.toByte (); //OK
PoseLocation fromByte = PoseLocation.fromByte (poseByte); //this does not work
Upvotes: 1
Views: 984
Reputation: 270780
You seem to think that fromByte
is also an extension method...
Look at the declaration carefully:
public static PoseLocation fromByte (byte poseByte)
Do you see the word this
? No. So it's not an extension method. It's just a normal static method like any other. To call a static method, you need to put the class in which it is declared in in front. In this case, fromByte
is declared in PoseLocationMethods
, so you should do:
PoselocationMethods.fromByte(1);
However, I don't think fromByte
belongs to the PoseLocationMethods
class. You might want to write an extension method for byte
:
public static PoseLocation ToPoseLocation(this byte poseByte) {
return (Poselocation)poseByte;
}
Alternatively, get rid of these To
and From
methods. I think using a cast is clear enough.
Upvotes: 1