Advertisement
//C# Calling a method with argument, by reference
//By passing it an object
using System;
class A
{
//Instance variable
int a;
//Defining the method Add()
//which is passed an object(by reference)
//to add a value to its instance variable, a
void Add(A ob)
{
ob.a = ob.a + 10;
}
//Defining the Main() method
public static void Main(String[] ar)
{
//Creating an object of A class
A ob = new A();
//Initializing the value of instance variable, i
ob.a = 100;
//Printing the value of local variable,a
//Before calling the Add() method
Console.WriteLine("Before calling the Add() method, the value in instance variable, a is: " + ob.a);
//Calling the Add method
//And passing it an object of class A
ob.Add(ob);
//Printing the value of local variable,a
//After calling the Add() method
Console.WriteLine("Afrer calling the Add() method, the value in instance variable, a is: " + ob.a);
}
}
Before calling the Add() method, the value in instance variable, a is: 100
Afrer calling the Add() method, the value in instance variable, a is: 110
Add(ob); // Add() method is called
//Defining the method Add()
//which is passed an object(by reference)
//to add a value to its instance variable, a
void Add(A ob)
{
ob.a = ob.a + 10;
}
Advertisement
//C# Example of calling a method by reference to call
//to swap or interchange the value in two char instance variables
using System;
class A
{
//Instance variables
char c, d;
//Defining the Swap_Char() method to swap characters
void Swap_Char(A ob)
{
char e;
e = ob.c;
ob.c = ob.d;
ob.d = e;
}
//Defining the Main() method
public static void Main()
{
//Creating an object of class A
A ob = new A();
//Initializing the char instance variables
ob.c ='x';
ob.d ='y';
//Printing the char instance variables before calling the Swap_Char() method
Console.WriteLine("The character value of instance variable c is: " + ob.c);
Console.WriteLine("The character value of instance variable d is: " + ob.d);
//Calling the Swap_Char() method of class A
//And passing it the object of class A
ob.Swap_Char(ob);
Console.WriteLine("After the Swap_Char() method is called");
//Printing the local char variables after calling the Swap_Char() method
Console.WriteLine("The character value of instance variable c is: " + ob.c);
Console.WriteLine("The character value of instance variable d is: " + ob.d);
}
}
The character value of instance variable c is: x
The character value of instance variable d is: y
After the Swap_Char() method is called
The character value of instance variable c is: y
The character value of instance variable d is: x
Advertisement
Advertisement
Please check our latest addition
C#, PYTHON and DJANGO
Advertisement