C# Returning Multiple Parameters

C# Returning Multiple Parameters

C# Returning Multiple Parameters

 In general, people who are new to software development learn about functions that do not return values, such as void, and functions that return a single value like int, string, float; however, as time passes and projects become more complex, functions that do not return a value or only return a single value become insufficient for us developers, and the question of how to return multiple values comes to mind.

If you have the same question in mind, your answer is in this article.

There are two types of functions that return multiple parameters: one is unnamed and the other is named functions that return multiple parameters. Let’s take a look at both.

Functions Returning Unnamed Multiple Parameters

    public (int, float) MultipleValueReturnFunction()
    {
        int intValue = 123;
        float floatValue = 123.123f;
        return (intValue, floatValue);
    }

    public void GetMultipleValue()
    {
        int returnedIntValue = MultipleValueReturnFunction().Item1;
        float returnedFloatValue = MultipleValueReturnFunction().Item2;
    }

As in the sample code above, you can return your parameters without naming them in your project and use them as "Item1", "Item2" in another function or wherever you want to use them.

Here, in the part public (int, float) FunctionName, the (int, float) indicates that this function returns multiple parameters, and we return our multiple parameters in accordance with the return(int, float) rule.

Functions Returning Named Multiple Parameters

    public (int intValue, float floatValue) NamedMultipleValueReturnFunction()
    {
        int i = 123;
        float f = 123.123f;
        return (intValue: i, floatValue: f);
    }

    public void GetNamedMultipleValue()
    {
        int returnedNamedIntValue = NamedMultipleValueReturnFunction().intValue;
        float returnedNamedFloatValue = NamedMultipleValueReturnFunction().floatValue;
    }

As in the example code above, you can name your parameters in your project and use them elsewhere with the names you provided.

Here, in addition to the unnamed multiple return function above, in the part public (int name, float name) FunctionName, the (int name, float name) part names the parameters we are returning.

As you can see, like the codes in the examples above, you can return multiple parameters from functions in your projects, and you can even give these parameters names and write more understandable code.