Since C# 7 you can make method signatures which correspond to multiple values
In Python, you can return multiple values from a function. This functionality is not however built-in into C#, shame. I think this is a nice feature of the language. It frequently reduces asymptotic complexity (i.e. "performance") without resorting to implementing another class to do it.
There are really 2 solutions to this problem: either arrays or custom class. Obvisouly, arrays are no good: you can't mix types.
1 2 3 4 5 |
string[] s = new string[2]; s[0] = "username"; s[1] = "password"; return s; |
Alternative is to implement a private class which would return the data one wants:
1 2 3 4 5 6 7 8 9 |
private class credentials { public string Username {get; private set;} public string Password {get; private set;} public Credentials(string username, string password) { Username = username; Password = password; } } |
I don't really have an issue with that other than naming can frequently be awkward and this looks like a lot of work for something that should be rather trivial.
The third alternative, and should address this issue: Tuples
. They are the recommended way to return multiple values from a function.
1 2 |
private Tuple<int, string> methodName() { return Tuple.Create(1, "Blah"); |
and to extract the values from the Tuple
we use predefined property Item1, Item2, Item3, etc...
. Tuples can be created with up to 8 values (but if you are returning more than 2 or 3 than we have a code smell).