4 ms·
var (ret, err) = Foo(); if (err != null) { ... }
by Leszek 10y ago
var (ret, err) = Foo();
if (err != null) {
...
}
- taco_emoji 10y agoSo Foo() has to return a class which has a destructor? Seems like just returning a Tuple would be better in that case.
- truncate 10y agoTuple in C# is a class IIRC. Without destructor, you will have to pull out individual members separately. For example for a tuple of form <Int, Int, Int>, you will do something like `var r = c.getFirst(); var g = c.getSecond();`. With deconstructor, you can do the same via `var (r, g, b) = color;`. In other words, you can say that tuples are way to combine data, while deconstructors tell how to explode it. Since these deconstructors are themselves functions, you can do computation each time, and get different results due to side-effects (probably not good idea). EDIT: I don't know C#, so syntax is definitely not right.
- EpicEng 10y agoYou would just check t.Item2, no need to assign to variables I'm this example. However, the deconstructor syntax is nice, and now tour functions don't all return Tuple with vaguely named members.
- truncate 10y agoRight. Not great example. What I wanted to say was deconstructor is all about creating new bindings with nicer syntax. You could just do that by calling getters / accessing fields, but you have to write more when you doing that.
- EpicEng 10y agoWell, it allows you to return multiple objects without using an opaque Tuple or creating your own class. Sure, the other options work, this is just a nicer syntax. I mean, I can all of what C# does in C if I want to, but I appreciate the syntactical sugar.
- mathw 10y agoBasically yes. Except, with the new tuple syntax support in C# it's using a value type internally instead of the old Tuple class (I'm pretty sure Tuple's going to be gaining a set of deconstructors to allow it to participate though). And the pure tuple path apparently doesn't use the deconstructors, there's something fancier going on under the hood which is presumably faster. But yes you can write a deconstructor for anything you like so it can participate in deconstructing assignment. And yes it can have side effects. And that would be VERY BAD.
- taco_emoji 10y agoOK, but that's not what the TFA describes as a deconstructor.
- will_hughes 10y agoIt's linked to providing these tuple types out of a method call. So instead of having to declare that Foo returns a FooReturn, it can be declared as (say) public (int ret, string err) Foo() { return (5, "something"); }
- taco_emoji 10y agoThat's not a deconstructor though, which is what the GP was asking about. EDIT: Looks like there's confusion... Yes, you can deconstruct a Tuple like this, but C# 7 also introduces a specific Deconstructor pattern in which ANY class can be deconstructed as though it were a Tuple.