Passing Arguments ByRef/ByVal

  • Thread starter Thread starter Scott M.
  • Start date Start date
S

Scott M.

Does C# support passing arguments ByVal & ByRef? If so, what is the default
(ByVal?)? And, if so, how do you explicitly specify either?

Thanks.
 
Scott M. said:
Does C# support passing arguments ByVal & ByRef?
Yes.

If so, what is the default (ByVal?)?
Yes

And, if so, how do you explicitly specify either?

int x = 1;
DoSomething(ref x);

void DoSomething(ref int x)
{
}

or

int x;
DoSomething(out x);

void DoSomething(out int x)
{
}
 
Scott said:
Does C# support passing arguments ByVal & ByRef? If so, what is the default
(ByVal?)? And, if so, how do you explicitly specify either?

Thanks.

As, Michael C pointed out - the answer is yes. The default, as in
VB.NET is by value (ByVal), but it is not specified explicitly.
Michael showed you that there are, in fact, two ways of passing by
reference (ByRef) in C# - but didn't clearly explain the difference. I
thought I might point that out...

The first way is via the ref keyword. It looks like this:

void SomeMethod (ref int theValue)

That says to pass, theValue by reference. But, the compiler will
require you to initialize the value before it is passed. So, when you
call the SomeMethod, it will look like:

int i = 10;
SomeMethod (ref i);

You can really think of ref as an In/Out parameter. Since, you can use
it to pass a value int and get a value back.

The second method, was via the out keyword. The out keyword does not
require the caller to initialize the value of the parameter. It is
required that the callee provide the value. If it doesn't then the
method will not compile:

void SomeMethod (out int theValue)

In this case, the usage would looke like:

int i;
SomeMethod (out i);

And again, SomeMethod would be required by the compiler to assign a
value to i. This is an Out parameter.

Anway - just thought I'd add a little bit more info to Michael's
excellent answer.
 
Thanks everyone. I was aware of ref and out and their requirements on having
a value set or not, but I was not aware that they caused the value to be
sent ByRef.
 

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

Back
Top