2

I have enum A which became two enums in version 2 enum B and C. There is a function GetSpecificEnum() which returns enum A for version 1 and should return enum B and C for version 2 and above. Function itself doing some calculations and returns enum which meets my scenario.

My problem is to properly define this function which can return two versions. I can always create two functions and somehow get calculations as private refactored method but i'm trying to avoid this.

Is there a way to do it ?

public ?? GetSpecificEnum() { if(version == 1) { //do some stuff return A.SomeValue; } else { // do some stuff return KeyValuePair<B, C>(B.SomeValue, C.SomeValue); } } 
2
  • could you show GetSpecificEnum() function code? Commented Mar 9, 2014 at 16:01
  • Would have been easier if this method returned int. Speaking of backward compatibility, what does method returns now? Edit: Never mind just reread. Commented Mar 9, 2014 at 16:14

2 Answers 2

3

You can use the system type Enum as the return value for GetSpecificEnum. Your code will then have to check the type for the return, and handle it accordingly.

 public enum A { ONE,TWO }; public enum B { THREE, FOUR }; public Enum GetThing(int version) { return version == 1 ? (Enum)A.ONE : B.THREE; } public void DoThing() { Enum e = GetThing(1); if (e is A) { // handle A A _a = (A)e; } else { // handle B } } 
Sign up to request clarification or add additional context in comments.

6 Comments

I would also recommend a generic version public T GetThing<T>(int version) where T : struct . Just to save the boxing/unboxing of the result
@ShlomiBorovitz I think his problem is that the calling function doesn't know what the expected enum type should be for the result. So how could it set T?
Mathew, how do i return Enum type i need when DoThing() is void ?
But he'll have to cast it eventually. well, if that would be somewhere else - then you're right.
@eugeneK GetThing or (in your version) GetSpecificEnum is the one which returns the enum
|
0

You could do something like this if you are an API/product provider:

 public enum OldEnum { One, Two, Three } public enum NewPart1 { One, Two } public enum NewPart2 { Three } [Obsolete("This method is intended to by used be previous versions")] public OldEnum GetEnum(someparameters here) { // Some processing here return OldEnum.One; } public NewPart1 GetEnum(someparameters here) { // Do something here return NewPart1.One; } public NewPart2 GetEnum(someparameters here) { // Do something here return NewPart2.Three; } 

If your enumerations are split of old enumeration, you do not really need to make change to code. In the end, we are dealing with integers. Please note, split enumerations still retain same integer values as earlier. You can then just cast the integer value and send it across.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.