Connecting Tech Pros Worldwide Forums | Help | Site Map

Parameters byref

Arne Garvander
Guest
 
Posts: n/a
#1: Jun 23 '06
I hace a function that needs to return two integers.
I know that objects can be passed by reference and updated in a function.
Can I do the same thing with primitive value type parameters?

--
Arne Garvander
(I program VB.Net for fun and C# to get paid.)

Tom Porterfield
Guest
 
Posts: n/a
#2: Jun 23 '06

re: Parameters byref


Arne Garvander wrote:[color=blue]
> I hace a function that needs to return two integers.
> I know that objects can be passed by reference and updated in a function.
> Can I do the same thing with primitive value type parameters?[/color]

Yes, just define the param as a ref int.
--
Tom Porterfield
Dan Manges
Guest
 
Posts: n/a
#3: Jun 23 '06

re: Parameters byref


Arne Garvander wrote:[color=blue]
> I hace a function that needs to return two integers.
> I know that objects can be passed by reference and updated in a function.
> Can I do the same thing with primitive value type parameters?
>[/color]

Arne,

You can pass in integers by reference. In C#:

private void UpdateInts(ref int one, ref int two)
{
}

However, depending on the purchase of your function, you may want to
consider returning an integer array with both integers.

Another option is to use output parameters. In C#:
private void UpdateInts(int something, out int one, out int two)
{
}

This will output two new values instead of updating the referenced integer.

Hope this helps.

Dan Manges
Tom Spink
Guest
 
Posts: n/a
#4: Jun 23 '06

re: Parameters byref


Arne Garvander wrote:
[color=blue]
> I hace a function that needs to return two integers.
> I know that objects can be passed by reference and updated in a function.
> Can I do the same thing with primitive value type parameters?
>[/color]

Hi Arne,

C# has two parameter modifiers to allow you to assign values to referenced
variables. Those modifiers are 'out' and 'ref'. There is a subtle
difference in that 'ref' is used to update the value of a parameter, i.e.
it MUST be assigned a value when it is passed in to the method, and the
method doesn't necessarily have to update it. The 'out' modifier is used
when a value SHOULDN'T be assigned when you pass the parameter in, and the
method MUST assign a value to it before it returns:

///
private void MyTestMethod ( )
{
int a, b;

MyOutMethod( out a, out b );
MyRefMethod( ref a, ref b );

Console.WriteLine( "A: {0}\nB: {1}", a, b );
}

private void MyRefMethod ( ref int a, ref int b )
{
a++;
b--;
}

private void MyOutMethod ( out int a, out int b )
{
a = 5;
b = 10;
}
///

I've totally just blitzed out that code without testing, but if all goes
according to plan, the output should be:

A: 6
B: 9

Hope this helps,
-- Tom Spink
Closed Thread