Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think it's good to create a new type when it makes sense to introduce a new value set into your program. For example, if you are writing a complex calculator, then make a complex number type. If you really just want to "glue" a few variables together for a moment, then a tuple is probably a better choice. Let's say you've got a simple function that gathers two numbers from the console... you might do something like:</p> <pre><code>static void GetNumbers(out int x, out int y) { ... } ... int x, y; GetNumbers(out x, out y); </code></pre> <p>I think it usually makes sense when a "getter" function has a return value but in this case it doesn't because I can't really have two return values. I could go and make a new type called TwoNumbers and use that but I think this quickly becomes more of a problem than a solution. If C# had tuples I may be able to do something like the following:</p> <pre><code>static (int, int) GetNumbers() { ... } ... int x, y; (x, y) = GetNumbers(); </code></pre> <p>Now the really interesting question is: although C# doesn't have this feature am I able to implement it myself with a library? The code you suggest is a start but won't allow me to assign like I've done in the second example. I'm not sure about C# but you can get really darn close to this in C++ by using the fact that <em>a function call can be the left operand to the assignment operator when it's return value is a reference type</em>. Consider the following:</p> <pre><code>// this class is implemented much like yours only with C++ template&lt;typename T1, typename T2&gt; class tuple { ... } ... template&lt;typename T1, typename T2&gt; tuple&lt;T1, T2&gt;&amp; tie(T1 a, T2 b) { ... } ... template&lt;typename T1, typename T2&gt; tuple&lt;T1, T2&gt; get_numbers() { ... } ... int x, y; tie(x, y) = get_numbers(); </code></pre> <p>I'd say that is pretty darn close... instead of <code>(x, y) =</code> we have <code>tie(x, y) =</code>. If you are interested in implementation details, I'll refer you to the TR1 library where I first learned about this:</p> <p><a href="http://www.boost.org/doc/libs/1_41_0/libs/tuple/doc/tuple_users_guide.html#tiers" rel="nofollow noreferrer">http://www.boost.org/doc/libs/1_41_0/libs/tuple/doc/tuple_users_guide.html#tiers</a></p> <p>So to bring all this back to C# 3.0... we can certainly create a generic tuple class as you've shown, but can we create a function like tie to "unpack" the tuple in C#? I haven't tried it, sounds like fun. Without something like that, I'd be reluctant to let a C# tuple library proliferate through my code. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload