Multiple Return Values in C#
C# supports multiple return values through the use of tuples. This feature is often used to return both result and error values from a function.
To run the program, save it as MultipleReturnValues.cs
and use the dotnet
command:
In C#, tuples provide a simple way to return multiple values from a method without the need to define a separate class or struct. The syntax (int, int)
in the method signature indicates that the method returns two integers.
When calling a method that returns a tuple, you can use tuple deconstruction to easily assign the returned values to separate variables. If you’re only interested in some of the returned values, you can use the discard pattern (_
) to ignore the others.
This approach offers a clean and efficient way to handle multiple return values in C#, similar to the idiomatic usage in other languages.
Tuple return types and deconstruction are powerful features in C# that enhance code readability and reduce the need for out parameters or custom classes for simple data structures.