Skip to main content

Passing Parameters by Value and Reference with Example in C#

 Passing Parameters by Value and Reference with Example in C#

Passing a Value-Type parameter to a method by value means passing a copy of the variable to the method. So the changes made to the parameter inside of the called method will not have an effect on the original data stored in the argument variable.

 In C#, Value-Type variable contain the value directly on its memory and Reference-Type variable will contain a reference of its data.

 Passing Parameters by Value Example in C#

Following is the example of passing a value type parameter to a method by value in C#.

 

static void Main(string[] args)

        {

            int x = 10;

            Console.WriteLine($"Variable Value Before Calling the Method: {x}");

            Multiplication(x);

            Console.WriteLine($"Variable Value After Calling the Method: {x}");

                      

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

 

        }

        public static void Multiplication(int y)

        {

            y *= y;

            Console.WriteLine($"Variable Value Inside the Method: {y}");

        }

  

From the above example, the variable x is a value type and its passed to the Multiplication method. The content of variable x copied to the parameter y and made required modifications in the Multiplication method but the changes made inside of the method have no effect on the original value of the variable.

 

Value Type

 


When we execute the above C# program, we will get the result as shown above.

 

 

From above result, the variable value not changed even after we made the modifications in our method.

 

Pass parameter by Reference (ref) in C#

 

Passing a value type parameter to a method by reference means passing a reference of the variable to the method. So the changes made to the parameter inside of the called method will have an effect on the original data stored in the argument variable.

 

By using the ref keyword, we can pass parameters reference-type and it’s mandatory to initialize the variable value before we pass it as an argument to the method in C#.

 

Declaration of C# Pass By Reference

The following is a simple example of passing parameters by reference in C#.

 

int r = 10; // Variable need to be initialized

Multiplication(ref r);

 

If we observe the above declaration, we declared and assigned a value to the variable r before we pass it as an argument to the method by using reference (ref).

 

To use the ref parameter in C# application, both the method definition and the calling method must explicitly use the ref keyword.

 

Passing Parameters by Reference Example in C#

 

The code below is an example of passing a value type parameter to a method by reference in C#.

 

 static void Main(string[] args)

        {

            int x = 10;

            Console.WriteLine($"Variable Value Before Calling the Method: {x}");

            Multiplication(ref x);

            Console.WriteLine($"Variable Value After Calling the Method: {x}");

                      

            Console.WriteLine("\nPress Enter Key to Exit..");

            Console.ReadLine();

 

        }

        public static void Multiplication(ref int y)

        {

            y *= y;

            Console.WriteLine($"Variable Value Inside the Method: {y}");

        }

From the above example, we are passing the reference of variable x to the variable y in Multiplication method by using the ref keyword. In this case, the variable contains the reference of variable x so the changes that made to the variable y will affect the value of variable x.

 

Reference Type


 

When we execute the above c# program, we will get the result as shown above.

 

If we observe the above result, the changes that we did for the variable in the called method have reflected in the calling method also.


References

1.    Tutlane

2.    Tutorial Teachers

Comments

Popular posts from this blog

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Routing

ASP.NET MVC Routing ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match. Routing pattern is as follows A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser. Route Properties ASP.NET MVC routes are res...

Role-Based Authorization in ASP.NET MVC

Role-Based Authorization Explained The most challenge aspect of any web application is implementing its security. In traditional web development with ASP.NET (from version 2.0 onwards), we have been using Membership and Role providers. These providers allows us to define Roles, Users and assign roles to users which helps us to manage Authorization. But with an increase in social networking and global authentication providers, we needed an upgraded membership system. ASP.NET Identity is the new membership system for building ASP.NET web applications, phone, store, or hybrid applications using social identities for authentication and authorization. So we can now use Windows Live (e.g. Hotmail), Gmail, Facebook and Twitter for authentication before the user starts using our web application. For internal application, we need to create users and roles for providing users access to creating items, products or managing other users. Necessary references are provided by MVC 5 applicatio...