Returning Multiple Values From a Method

Haydar Ali Ismail
2 min readFeb 12, 2017

Recently, I’m required to make a method to calculate a linear equation. As we know that the linear equation is y = mx + b. So, I’m required to make the method return several values: y, m, x, and b. By default, we can only return a single variable from a method. So, we need to apply some trick in order to do so. Aside from the problem I’m facing, actually it might happen in other cases. So, today I’m going to give an insight of some ways to return the multiple values from a method. The examples are in C#, but my point is to tell you the way of thinking, not the actual implementation.

Methods

1. Using Global Variables (Not Recommended)

It is by far the easiest one. We can store the result into global variables. An example is available below.

The problem with this method is that when the global variables modified in a lot of methods, that can be troublesome. Because if we are not careful about the order of the method calls, then the order of variables modifications can be not as what we expect thus making the outcome of the variables is not as we expect. To accommodate that there are better alternatives.

2. Using Dictionary or HashMap

In my opinion, it’s better than using global variables, but still easy enough to do. Depending on the programming languages, we can use dictionary or hashmap. Basically, the method is going to return a dictionary or hashmap containing all the values that we want to get. To get a better illustration, here is an example.

The example above is in C#. Then after we assign those variables to the dictionary, we can return the dictionary. Thus, when we want to access the value, we can access it from the dictionary. The problem with this method is that we can only assign multiple values with same data type. If you want to attach multiple data types, then you have the last option.

3. Using Class (Best Solution)

One of the most obvious, but sometimes it’s overkill. Basically, all we need to do is to create the model for the values that we want to return. Then we just simply return the model we already created. Here is an illustration for that.

There is basically no problem with this method. The problem is that sometimes it’s just overkill because we might only use the class once. Other than that, it’s actually the best solution.

Wrap Up

The purpose this story is to give you insight and idea how to solve the following problem. There might be other solution out there to solve this problem. But, by far there are solutions that I can think of. Hope you can get benefits from reading this story. Thank you for reading.

--

--