First way Tuple, our new class comes with .net 4.0.
- using System;
- namespace Test
- {
- class Program
- {
- public static Tuple<int, string> ReturnTuple()
- {
- int i = 0;
- string str = string.Empty;
- //Do something
- //There is two way to create a tuple object
- return Tuple.Create(i, str);
- //return new Tuple<int, string>(i, str);
- }
- static void Main(string[] args)
- {
- int myInt;
- string myString;
- Tuple<int, string> myTuple = ReturnTuple();
- myInt = myTuple.Item1;
- myString = myTuple.Item2;
- Console.WriteLine("{0:d}-{1}", myInt, myString);
- }
- }
- }
Second way use ref, out keywords.
- using System;
- namespace Test
- {
- class Program
- {
- public static int UseOut(out string str)
- {
- int i = 0;
- str = string.Empty;
- //Do something
- return i;
- }
- static void Main(string[] args)
- {
- int myInt;
- string myString;
- myInt = UseOut(out myString);
- Console.WriteLine("{0:d} - {1}", myInt, myString);
- }
- }
- }
You can create your custom classes or structs and return them. These classes will include return variables.
- using System;
- namespace Test
- {
- class Program
- {
- public static ReturnValues ReturnCustomStruct()
- {
- ReturnValues rv;
- int i = 0;
- string str = string.Empty;
- //Do something
- rv.ValueInt = i;
- rv.ValueString = str;
- return rv;
- }
- static void Main(string[] args)
- {
- int myInt;
- string myString;
- ReturnValues rv = ReturnCustomStruct();
- myInt = rv.ValueInt;
- myString = rv.ValueString;
- Console.WriteLine("{0:d} - {1}", myInt, myString);
- }
- }
- struct ReturnValues
- {
- public int ValueInt;
- public string ValueString;
- }
- }
4th way. Use List or Array
- using System;
- using System.Collections.Generic;
- namespace Test
- {
- class Program
- {
- public static List<object> ReturnList()
- {
- int i = 0;
- string str = string.Empty;
- //Do something
- }
- static void Main(string[] args)
- {
- int myInt;
- string myString;
- List<object> list = ReturnList();
- myInt = Convert.ToInt32(list[0]);
- myString = list[1].ToString();
- Console.WriteLine("{0:d} - {1}", myInt, myString);
- }
- }
- }
Join return variables string or serialization values with a separator.
- using System;
- namespace Test
- {
- class Program
- {
- public static string JoinReturnValues()
- {
- int i = 0;
- string str = string.Empty;
- //Do something
- //separator |
- string returnValue = string.Join("|", i, str);
- return returnValue;
- }
- static void Main(string[] args)
- {
- int myInt;
- string myString;
- string s = JoinReturnValues();
- myInt = Convert.ToInt32(sArray[0]);
- myString = sArray[1].ToString();
- Console.WriteLine("{0:d} - {1}", myInt, myString);
- }
- }
- }
If you are going to return two values you can use KeyValuePair class. There are some other ways too. We can use GLOBAL variables or XML.