Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to 'do' ByVal in C#

Tags:

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 Visual Basic 6.0, 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.

like image 443
Jouke van der Maas Avatar asked Jun 14 '10 20:06

Jouke van der Maas


People also ask

How do you use ByRef and ByVal?

ByRef = You give your friend your term paper (the original) he marks it up and can return it to you. ByVal = You give him a copy of the term paper and he give you back his changes but you have to put them back in your original yourself. As simple as I can make it.

What is ByVal?

ByVal stands for By Value i.e. when the subprocedure called in from the procedure the value of the variables is reset to the new value from the new procedure called in.

What is the use of ByVal?

Forces a parameter to be passed by value rather than by reference. The ByVal keyword can appear before any parameter passed to any function, statement, or method to force that parameter to be passed by value. Passing a parameter by value means that the caller cannot modify that variable's value.

Is C# ByRef or ByVal?

C# Passing arguments by default is ByRef instead of ByVal.


2 Answers

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)
like image 189
Marc Gravell Avatar answered Sep 24 '22 18:09

Marc Gravell


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.

like image 39
Tim Goodman Avatar answered Sep 23 '22 18:09

Tim Goodman