views:

193

answers:

3

As I understand it, C# passes parameters into methods by reference. In vb.net, you can specify this with ByVal and ByRef. The default is ByVal.

Is this for compatibility with vb6, or is it just random? Also, how can I specify what to use in C#? I kind of like the idea of passing parameters by value.

+6  A: 

Parameters in C# are passed "ByVal" by default. You have to specify "ref" or "out" if you want different behavior.

Reed Copsey
+19  A: 

Parameters in C# are, by default passed by value. There is no modifier to make this explicit, but if you add ref / out the parameter is by-reference.

The usual confusion here is the difference between:

  • passing a value-type by value (changes to the value-type are not visible to the caller, but value-types should ideally be immutable anyway)
  • passing a value-type by reference (changes to the value-type are visible to the caller, but value-types should ideally be immutable anyway - so important I'll say it twice ;p)
  • passing a reference by value (changes to fields/properties of the ref-type are visible to the caller, but reassigning the ref-type to a new/different object is not visible)
  • passing a reference by reference (changes to fields/properties, and reassigning the reference are visible to the caller)
Marc Gravell
Thanks, that was exactly what caused my confusion.
Jouke van der Maas
When I first started I used `ref` everywhere because i thought that was the C# equivalent of passing a pointer ;<
Jake
+5  A: 

Passing by value is the default in C#. However, if the variable being passed is of reference type, then you are passing the reference by value. This is perhaps the origin of your confusion.

Basically, if you pass a reference by value, then you can change the object it refers to and these changes will persist outside the method, but you can't make variable refer to a different object and have that change persist outside the method.

Tim Goodman
Marc Gravell edited basically this same info into his answer while I was typing this, making this answer kind of redundant I guess.
Tim Goodman
Your answer still has some value, since it directly addresses the distinction between modifying the reference and modifying the instance. Besides, it's best not to compare yourself to the "people" with 50+k rankings: I have it on good authority that Reed is an AI run by Google, and most of the others are likewise non-human. :-)
Steven Sudit
@Steven: Good point :-)
Tim Goodman