C# Returning an enum and an int array
I'm working开发者_高级运维 on something where I would need to return an enum and an array of ints. I can go around the whole issue and use an int instead of the enum and add it as the first element of the array, but the enum really helps my code legibility. Is there any way to return both at the same time?
There are 3 common solutions to this. Which one is appropriate would depend on the specific situation and your personal preference:
Use an
out
parameter for one of them. This doesn't require any new types, but is inconvenient to call. Additionally, it may not semantically capture the relationship between the returned values.public int[] MyMethod(out MyEnumType myEnum) { myEnum = ... int[] nums = ... return nums; }
Use the
Tuple<,>
type (.NET 4.0). This only requires the construction of a closed generic-type from an existing BCL type, but callers may not like the fact that the encapsulated properties have meaningless names:Item1
andItem2
You can also theKeyValuePair<,>
type or write your ownPair<,>
type to serve a similar purpose.public Tuple<int[], MyEnumType> MyMethod() { int[] nums = ... MyEnumType myEnum = ... return Tuple.Create(nums, myEnum); }
Write a wrapper class that encapsulates the int array and the enum. More work, but nicest to work with for the caller.
public class Wrapper { public int[] Nums { get { ... } } public MyEnumType MyEnum { get { ... } } } ... public Wrapper MyMethod() { Wrapper wrapper = ... return wrapper; }
精彩评论