LogIn
I don't have account.

C# Method or Function call by Reference

DevSniper
189 Views

  • Any changes in this type of parameter will reflects on parent or caller method variables.
  • if we pass reference type variable from one method to another method the system will not create a seprate copy of that variable. it will pass same memory location in other method so that if we change variable value in other method that will reflects to parent or caller method.
using System;

class Student
{
    public int Id {get; set;}
    public string Name {get; set;}
    public int Age {get; set;}
    public Student(int id,string name,int age)
    {
        Id=id;
        Name=name;
        Age=age;
    }
    public void print()
    {
        Console.WriteLine($"\tId : {Id} , Name : {Name} and  Age : {Age}");
    }
}
class Program
{
    public static void fun(Student student)
    {
        Console.WriteLine("Inside fun before updating age :- ");
        student.print();
        student.Age+=5;
        Console.WriteLine("Inside fun after updating age :- ");
        student.print();
    }
    static void Main()
    {
        var student = new Student(111,"Ram",25);
        Console.WriteLine("Inside main method :- ");
        student.print();
        fun(student);
        Console.WriteLine("Inside main method after calling fun :- ");
        student.print();
    }
}
Inside main method :- 
        Id : 111 , Name : Ram and  Age : 25
Inside fun before updating age :- 
	Id : 111 , Name : Ram and  Age : 25
Inside fun after updating age :- 
	Id : 111 , Name : Ram and  Age : 30
Inside main method after calling fun :- 
	Id : 111 , Name : Ram and  Age : 30