return multiple values

  • Thread starter Thread starter Aaron
  • Start date Start date
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]
 
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é
 
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]
 
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)
 
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;
}
 
Back
Top