In this post, I will explain different ways to return multiple values from a method without using pre-defined custom struct or class definition.
-
Tuple
First we can use
Tuplereturn type, for example in below exmaple,Method1()is the method which will return mulitple values, andMethod2()will callMethod1()to receive the returned value.private Tuple<string, int> Method1(long id) { //get data from DB for given 'id' return Tuple.Create("Kamran", 25); } private void Method2() { var user = Method1(1); Console.WriteLine($"UserName = {user.Item1}, Age = {user.Item2}"); }Tuples with two values have properties named
Item1andItem2. For more properties it will be name in same sequenceItem3,Item4,Item5and so on...In above exmaple, In
Method2(), theuserobject(Tuple) has two properties,Item1andItem2, which will have same data types respectively as defined inMethod1()'sreturned tuple. In this case,Item1will be ofstringtype, andItem2will be ofinttype.Another way to consume/receive tuple value is to use deconstructor syntax.
Method2()in above exmaple can also be written like this:private void Method2() { (string username, int age) = Method1(1); Console.WriteLine($"UserName = {username}, Age = {age}"); }Here the returned value from tuple's items will be deconstructed to local variables
usernameandage.Second way to create and return tuple is without Tuple keyword. You have to define types for each tuple item in parenthesis.
private (string , int) Method1(long id) { //get data from DB for given 'id' return ("Kamran", 25); }As before, Tuple's items has items with names Item1, Item 2 and so on... If you want to explicitly define elements with your own name, you can use this syntax.
private (string username, int age) Method1(long id) { return ("Kamran", 25); }Now you can access tuple's items by names.
private void Method2() { var user = Method1(1); Console.WriteLine($"UserName = {user.username}, Age = {user.age}"); } -
Dynamic Type
Second way to return multiple values by single method is to use
dynamictype object.private static dynamic Method1(long id) { dynamic temp = new System.Dynamic.ExpandoObject(); temp.Username = "Kamran"; temp.Age = 25; return temp; }Consume
dynamictype object returned from above method.private void Method2() { var user = Method1(1); Console.WriteLine($"UserName = {user.Username}, Age = {user.Age}"); }Note that you will lose intellisense support and compile time type checking with dynamic type.
-
KeyValuePair
Another way to return multiple values is to use
KeyValuePair.private KeyValuePair
Method1(long id) { return new KeyValuePair ("Kamran", 25); } Consume
KeyValuePairobject returned from above method.private void Method2() { var user = Method1(1); Console.WriteLine($"UserName = {user.Key}, Age = {user.Value}"); }Note that
KeyValuePairobject have onlyKeyandValueparts, so you can use it to return two values maximum. If you want to return more than two values, thenKeyValuePairis not a best fit.
No comments:
Post a Comment