Return multiple values from method

  • Thread starter Thread starter YoYo Pa
  • Start date Start date
Y

YoYo Pa

I'm new to C#, and wondering how to return multiple values from a method. I
need to have a method return 3 int and 1 string.

thanks
 
No, but you can use some "out" parameters to send them back to the client.
Or you can create a structure that encapsulates what you want returned.
 
Hi Yo,

You can either declare that method of yours ot return a structure of those
ints and string or return the result thru method's parameters

public void Foo(out int intParam1, out int intParam2,out int intParam3,out
strung strParam)
{
......
}
 
You can either

1) return an instance of a class that encapsulates your multiple return values or return a structure that encapsulates them. The former gives you return-by-reference semantics, the latter return-by-value

2) use multiple "out" parameters to return the values

-- Thomas Brow
 
Thanks Stoitcho
How does the caller of your sample Foo() method retrieve the output
parameter values? What does that code look like.

-Yo



Stoitcho Goutsev (100) said:
Hi Yo,

You can either declare that method of yours ot return a structure of those
ints and string or return the result thru method's parameters

public void Foo(out int intParam1, out int intParam2,out int intParam3,out
strung strParam)
{
.....
}

---
HTH
B\rgds
100 [C# MVP]

YoYo Pa said:
I'm new to C#, and wondering how to return multiple values from a
method.
I
need to have a method return 3 int and 1 string.

thanks
 
Hi Yo,

--- Caller---
int i1, i2, i3;
string str;

Foo(out i1, out i2, out i3, out str);
//At this point on i1, i2, i3 and str has their values
-------

--- Foo ---
In Foo body Treat intParam1, intParam2,intParam3 and strung strParam as you
treat any other uninitialized local variable.
Becuse *out* modifier is used you have to give values to them before leave
the method. Otherwise the code won't compile.

--
HTH
B\rgds
100 [C# MVP]

YoYo Pa said:
Thanks Stoitcho
How does the caller of your sample Foo() method retrieve the output
parameter values? What does that code look like.

-Yo



Stoitcho Goutsev (100) said:
Hi Yo,

You can either declare that method of yours ot return a structure of those
ints and string or return the result thru method's parameters

public void Foo(out int intParam1, out int intParam2,out int intParam3,out
strung strParam)
{
.....
}

---
HTH
B\rgds
100 [C# MVP]

YoYo Pa said:
I'm new to C#, and wondering how to return multiple values from a
method.
I
need to have a method return 3 int and 1 string.

thanks
 
Back
Top