return multiple values

A

Aaron

can a method return multiple values?

pseudo code

public string method1()
{
//db pull

select col1, col2, from tb1
s1 = col1;
s2 = col2;

return s1, s2?
}

string1 = method1[s1]
string2 = method1[s2]
 
J

José Joye

Normally in such a situation the best is to return an object that is
constructed within your method and that will expose, as property, data you
have initialized within your method.

José
 
A

Aaron

could you give me an example?

im new to c#

thanks
José Joye said:
Normally in such a situation the best is to return an object that is
constructed within your method and that will expose, as property, data you
have initialized within your method.

José
Aaron said:
can a method return multiple values?

pseudo code

public string method1()
{
//db pull

select col1, col2, from tb1
s1 = col1;
s2 = col2;

return s1, s2?
}

string1 = method1[s1]
string2 = method1[s2]
 
J

Jon Skeet [C# MVP]

Aaron said:
can a method return multiple values?

Not directly, no. Possibilities are:

o Return an array of values instead (this looks fairly appropriate in
your example)
o Return a composite object which is the logical representation of all
those values (this makes sense in terms of a method only doing one
thing)
o Use ref/out parameters (rarely a good idea in terms of clean
separation etc, but can avoid you making extra classes just for the
sake of returning them)
 
M

Morten Wennevik

struct thingy
{
public column s1;
public column s2;
}

public thingy method1()
{
select col1, col2, from tb1
thingy t = new thingy();
t.s1 = col1;
t.s2 = col2;
return t;
}

Another way would be to use ref or out

column s1;
column s2;

public void method1(out value1, out value2)
{
select col1, col2, from tb1
value1 = col1;
value2 = col2;
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top