.NET4でタプルという機構が追加されています。任意の型のインスタンスを任意の個数保持できるクラスです。
Tuple クラス (System)
組オブジェクトを作成するための静的メソッドを提供します。 ...
# リファレンスでは「組」と訳されてるけど「タプル」の方がわかりやすいと思う。
ソースコード
private static Tuple<bool, int> TryParse(string value) { int i; Tuple<bool, int> result = Tuple.Create(int.TryParse(value, out i), i); return result; } static void Main(string[] args) { Tuple<bool, int> result = TryParse("1"); if (result.Item1) Console.WriteLine(result.Item2); else Console.WriteLine("Error"); }
メリット
Object型の配列を使用する実装と比較したときのメリットは、
- タイプセーフ(キャストが不要)
- IndexOutOfRangeExceptionが発生しない
といったところでしょうか。