What is the difference between ByVal and ByRef in VB.NET?
Quick Answer
ByVal (the default in VB.NET) passes a copy — the method can't change the caller's variable. ByRef passes a reference to the variable itself, so assignments inside the method are visible to the caller — the equivalent of C#'s ref.
ByVal passes a copy, so the method can't change my variable — and that's the default in VB.NET if you don't write a keyword. ByRef passes the variable itself, so if the method assigns to the parameter, I see that change back in the caller; it's the same as ref in C#. One gotcha when porting old code: VB6 defaulted to ByRef, so parameters that used to be modifiable become copies under VB.NET's default.
- For a value type,
ByValcopies the value;ByReflets the method replace it. - For a reference type,
ByValcopies the reference — you can still mutate the object's members, but reassigning the parameter doesn't affect the caller.ByReflets you reassign it. - VB.NET defaults to
ByValif you omit the keyword (older VB6 defaulted toByRef— a common source of bugs when porting). - Use
ByRefsparingly; a return value or a tuple is usually clearer.