Saturday, November 08, 2008

Extracting named variables from an array

My code uses the following pattern in a lot of places:

  1. string[] array = GetSomeData();  
  2. Debug.Assert(array.Length() >= 3);  
  3. m_Member = array[0];  
  4. m_Password = array[1];  
  5. m_SomeOtherInfo = array[2];  


... and so on. This is happening often enough that I tried finding a clearer way of expressing it. I even asked a question on stackoverflow. The answers I got aren't bad, but I came up last night with a solution I like more. (It doesn't mean it's the best, and it does look a little kludgy, but I like the way my code looks.)

  1. using System.Diagnostics;  
  2.   
  3. public static class ArrayExtractor  
  4. {  
  5.   public static void Extract<T1>(this object[] array, out T1 value1)  
  6.       where T1 : class  
  7.   {  
  8.     Debug.Assert(array.Length >= 1);  
  9.     value1 = array[0] as T1;  
  10.   }  
  11.   
  12.   public static void Extract<T1, T2>(this object[] array, out T1 value1, out T2 value2)  
  13.       where T1 : class  
  14.       where T2 : class  
  15.   {  
  16.     Debug.Assert(array.Length >= 2);  
  17.     value1 = array[0] as T1;  
  18.     value2 = array[1] as T2;  
  19.   }  
  20. }  


This only shows the code for 2 values, I'm going to write it for up to 10 values or so. It's not as elegant as the other solutions but now I can simply write

  1. string fileName;  
  2. string contents;  
  3. ArrayExtractor.Extract(array, out fileName, out contents);  


or even better

  1. array.Extract(out fileName, out contents);  

No comments: