One of the biggie challenges when programming in any language is figuring how to group and organize things sensibly. Even a small project can get out of hand quickly, and once you’ve got a dozen devs working in something for years, all bets are off.
So we have methods and functions, organized into classes (even JS has classes now) and namespaces, separate projects and assemblies, and on and on. The tricky part of having so many ways to organize things is knowing how and when to use one of them. A lot of it’s up for debate (what isn’t?) and some of it’s not… I wouldn’t recommend publishing a NuGet package for a few lines of code, lol.
The code in this article is available on GitHub, if you’d like to use it in your own projects or just follow along while you read.
In C#, it’s not uncommon to use classes to group similar logic together, and then provide properties to access whatever values are in the class - a person with a name and birthdate, a car with an engine type and model, whatever. If you’re going to have lots of properties, a class probably makes sense. But what if you don’t? If there’s a more lightweight option than a class and a good use case for it, I’d be interested in hearing about it.. or writing about it as the case may be.
|
|
One alternative is to create a method with several “out” parameters.
|
|
I used to think that was ugly since we had to define the variables before calling the method, but now they can be defined right as we call the method so it’s a lot more palatable. That was introduced in C# 7.0.
|
|
Another alternative, and the one I want to really focus on, is using tuples. I used to like them even less than “out” parameters, since whatever values you returned were only accessible by referencing .Item1
, .Item2
, etc. You immediately lost context of what was being returned.. very unfriendly. There have been some major changes though since C# 7.0, and it makes tuples much easier on the eyes.. brain… something. They’re easier to work with.
Here’s an example that’s pretty similar to the one above using “out” parameters, but it returns a tuple type instead. Since tuple types can have field names too, this really seems to behave more like a class to me.
|
|
Being able to access each element of the tuple by name makes this soo much friendlier than in the past.
|
|
You can desconstruct a tuple if you’d like, assigning all the elements in one place, which is similar to how the “out” example works.
|
|
And if you don’t need all of the elements, you can even discard them. Here’s an example where all I needed was the area of the circle, so I discarded the rest.
|
|
What do you think? Like it more than classes and “out” variables? Love it? Hate it? Or do you have your own way of returning multiple values at once?
If you found this content useful, and want to learn more about a variety of C# features, check out this GitHub repo, where you’ll find links to plenty more blog posts and practical examples!