Click here to Skip to main content
15,921,837 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I wanna want to return two outputs in a method ...is that possible ???
Posted
Updated 23-Jun-13 7:47am
v3

Not via a return statement - a method can only ever return a single object.

There are two ways to do what you want:
1) Return an object which contains the two (or more) values you need:
C#
private KeyValuePair<string, int> MyMethod()
    {
    ...
    return new KeyValuePair<string, int>("hello", 666);
    }

2) Add an out or ref parameter:
C#
private string MyMethod(out int iValue)
    {
    ...
    iValue = 666;
    return "hello";
    }


[edit]int parts of KeyValuePair declarations vanished... - OriginalGriff[/edit]
 
Share this answer
 
v2
Hi,

Instead of a KeyValuePair, you can also use a Tuple:
http://msdn.microsoft.com/en-us/library/dd268536.aspx[^]
C#
private Tuple<string,int> MyMethod()
    {
    ...
    return new Tuple<string,int>("hello", 666);
    }

C#
Tuple<string,int> x = MyMethod();
string str = x.Item1;
int i = x.Item2;

There's not only a Tuple with 2 elements: there're Tuples with 1, 2, 3, 4, 5, 6, 7 and 8 elements: http://msdn.microsoft.com/en-us/library/system.tuple.aspx[^]

Hope this helps.
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900