Changing Signatures Refactorings – Convert to Tuple
The Convert to Tuple refactoring shipped in Refactor! Pro is similar to the Introduce Parameter Object refactoring, but it doesn’t create a new object – it uses the built-in .NET Framework 4.0 Tuple object.
The Tuple object should have at least one component, and can have a maximum of 8 components. So, there are 8 different Tuple classes:
- Tuple<T1>
- Tuple<T1, T2>
- Tuple<T1, T2, T3>
- Tuple<T1, T2, T3, T4>
- Tuple<T1, T2, T3, T4, T5>
- Tuple<T1, T2, T3, T4, T5, T6>
- Tuple<T1, T2, T3, T4, T5, T6, T7>
- Tuple<T1, T2, T3, T4, T5, T6, T7, TRest>
You can instantiate a new Tuple object using any of these classes depending on the number of arguments you will pass. Also, there is the special static Tuple.Create method which has 8 overloads, each of them taking 1 … 8 arguments. The Tuple object will expose the Item1 … Item8 properties, returning the values of the passed-in arguments of the appropriate type. Actually, Tuple supports more than 8 arguments as it expects the 8th argument as another Tuple, e.g.:
Tuple<Int32, Int32, Int32, Int32, Int32, Int32, Int32, Tuple<String, String, String>>
Here’s a sample where the Convert to Tuple might be useful. The sample method imports some data into an SQL data base. The data consists of four objects – we’ll store these objects as a single Tuple object.