Best practice to return multiple variables from a method

Soldato
Joined
22 Oct 2005
Posts
2,803
Location
Moving...
I've inherited some code that runs automated tests using Selenium, NUnit and C#.

I've noticed there's lot of repeated code in some tests where the same calculations are done in multiple tests. It makes sense to me to move this calculation to a separate method to avoid duplicating code.

The problem I have is that (in my head at least) the ideal solution is to pass this new method two variables, then have the method do some fancy calculations and return four variables. However, it looks like methods are only designed to return single variables.

Is there a way to return multiple variables from a method, or am I approaching things the wrong way? All the variables (in these tests at least) are defined locally within the test rather than globally.

As you can tell I'm a bit of a novice so am looking to do things the correct way rather than just bodge something together!
 
Soldato
Joined
28 Oct 2006
Posts
12,456
Location
Sufferlandria
Create a new class with properties for each of the 4 variables.
Create an instance of this class inside the method, assign the 4 calculation results to it's properties and return the class object.
 
Soldato
Joined
20 Dec 2004
Posts
16,027
As described, returning an object wrapping the results.

Be careful you're not mangling your code to make the tests easier. If there is just one general purpose algorithm that is being tested in 4 different ways.....you don't want to break the re-usability of the algorithm by making a concrete implementation that only works for your 4 test cases.

If there's some pre and post-calculations being done to prepare the tests, consider moving them into a re-usable test method, rather than refactoring the program code.
 
Back
Top Bottom