What is the difference between ByVal and ByRef in VB.NET?

VB.NET Language Basic Fresher1–2 Yrs Conceptual 1 min read

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, ByVal copies the value; ByRef lets the method replace it.
  • For a reference type, ByVal copies the reference — you can still mutate the object's members, but reassigning the parameter doesn't affect the caller. ByRef lets you reassign it.
  • VB.NET defaults to ByVal if you omit the keyword (older VB6 defaulted to ByRef — a common source of bugs when porting).
  • Use ByRef sparingly; a return value or a tuple is usually clearer.