VB.NET tutorial-passing parameters ByVal ByRef


VB.NET Sub-procedure and Function

Passing parameters ByVal ByRef

Parameters can be passed to a sub-procedure or a function by ByVal or ByRef. If you pass the parameters by ByVal, their values cannot be changed by called sub-procedure or function.
Example:
Module Module1
 
    Sub Main()
        Dim result As Integer
        Dim x, y As Integer
        Console.Write("Enter value1:")
        x = CInt(Console.ReadLine)
        Console.Write("Enter value2:")
        y = CInt(Console.ReadLine)
        Console.WriteLine("Original x=" & x & " Original y=" & y)
        result = sum2values(x, y) 'calling the function with 2 parameters
        Console.WriteLine("Result=" & result)
        Console.WriteLine("x after trying to make change=" & x & ", y after trying to make change=" & y)
        Console.ReadLine()
 
    End Sub
    'defining a function with 2 parameters
    Function sum2values(ByVal x, ByVal y)
        'modifying values of x and y
        x = 80
        y = 100
        sum2values = x + y
 
    End Function
End Module

 


In contrast, if you pass the parameters by ByRef, their values can be changed by called sub-procedure or function.
Example:

 


Module Module1
 
    Sub Main()
        Dim result As Integer
        Dim x, y As Integer
        Console.Write("Enter value1:")
        x = CInt(Console.ReadLine)
        Console.Write("Enter value2:")
        y = CInt(Console.ReadLine)
        Console.WriteLine("Original x=" & x & " Original y=" & y)
        result = sum2values(x, y) 'calling the function with 2 parameters
        Console.WriteLine("Result=" & result)
        Console.WriteLine("x after trying to make change=" & x & ", y after trying to make change=" & y)
        Console.ReadLine()
 
 
    End Sub
    'defining a function with 2 parameters
    Function sum2values(ByRef x, ByRef y)
        'modifying values of x and y
        x = 80
        y = 100
        sum2values = x + y
 
    End Function
End Module


Comments

CAPTCHA image




This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.