Extracting named variables from an array
My code uses the following pattern in a lot of places:
... 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.)
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
or even better
- string[] array = GetSomeData();
- Debug.Assert(array.Length() >= 3);
- m_Member = array[0];
- m_Password = array[1];
- 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.)
- using System.Diagnostics;
- public static class ArrayExtractor
- {
- public static void Extract<T1>(this object[] array, out T1 value1)
- where T1 : class
- {
- Debug.Assert(array.Length >= 1);
- value1 = array[0] as T1;
- }
- public static void Extract<T1, T2>(this object[] array, out T1 value1, out T2 value2)
- where T1 : class
- where T2 : class
- {
- Debug.Assert(array.Length >= 2);
- value1 = array[0] as T1;
- value2 = array[1] as T2;
- }
- }
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
- string fileName;
- string contents;
- ArrayExtractor.Extract(array, out fileName, out contents);
or even better
- array.Extract(out fileName, out contents);
Comments