Using the 'ref' keyword.

  • Thread starter Thread starter Elad Gutman
  • Start date Start date
E

Elad Gutman

Hello,

Something is quite puzzled to me in using the 'ref' keyword, probably
due to some lack of basic understanding.
Whenever I wanna change the parameter passed to a function I will use
the 'ref' keyword, that's fine, and it even makes sense when sending a
Value Type parameter (int, float or a struct, for example). However, if
I'm sending a class object to the function, and this object is a
Reference Type, of course, isn't it being sent Byref as a default
behavior because it's a Reference value??? When sending a Reference
Type to a function is it being sent Byval and therefore I have to use
the 'ref' keyword?

What am I missing here?

Thanks,

Elad
 
Elad,

A reference type and sending a parameter by reference are two different
things. If you send a reference type to a method (passed by value), then
the reference is passed by value. Since you are sending a reference, you
can still access the same object outside of the method using another
variable set to the same reference.

Now, if you pass that reference by ref, you can modify the value of that
parameter so that it holds a new reference to a new object. When you pass
it by value, you can't do that.

Hope this helps.
 
Elad Gutman said:
Something is quite puzzled to me in using the 'ref' keyword, probably
due to some lack of basic understanding.
Whenever I wanna change the parameter passed to a function I will use
the 'ref' keyword, that's fine, and it even makes sense when sending a
Value Type parameter (int, float or a struct, for example). However, if
I'm sending a class object to the function, and this object is a
Reference Type, of course, isn't it being sent Byref as a default
behavior because it's a Reference value??? When sending a Reference
Type to a function is it being sent Byval and therefore I have to use
the 'ref' keyword?

The reference is sent by value by default - you can change the object
itself, but not *which* object is referred to.

See http://www.pobox.com/~skeet/csharp/parameters.html for more
information.
 
Thank you all for the quick respond. The reference( . . . -:) to the
article is just great!

Elad
 
Back
Top