简体   繁体   中英

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:

  1. 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; } 
  2. 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 and Item2 You can also the KeyValuePair<,> type or write your own Pair<,> type to serve a similar purpose.

     public Tuple<int[], MyEnumType> MyMethod() { int[] nums = ... MyEnumType myEnum = ... return Tuple.Create(nums, myEnum); } 
  3. 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; } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM