How to Pass an Object as an Argument into Method in C#?
Last Updated :
06 Dec, 2021
Given an object, now we pass this object as an argument into the method in C#. Here, a method is a code block that contains a series of statements that will only execute when the method is called. We can pass the data to the methods in form of arguments and an object is an instance of a class that is created dynamically. The basic data types can be passed as arguments to the C# methods in the same way the object can also be passed as an argument to a method. But keep in mind that we cannot pass a class object directly in the method. We can only pass the reference to the object in the method.
// Creating the demo object
demo d1 = new demo(6);
// Passing object as an argument to the PassObj method.
d1.PassObj(d1);
Example 1:
C#
// C# program to pass an object as an argument into method
using System;
// Creating a class named demo
class demo
{
int value;
// Constructor to initialize the variable value
public demo(int val)
{
value = val;
}
// Method in which we pass the object as a argument
public void PassObj(demo d2)
{
Console.WriteLine(d2.value);
}
}
// Driver code
class GFG{
static void Main()
{
// Creating the demo object
demo d1 = new demo(6);
// Passing object as an argument to
// the PassObj method.
d1.PassObj(d1);
}
}
Explanation: In the above example, first we create a class named "demo" with a constructor to initialize an integer variable. It also has a method named PassObj() which takes one parameter. Now in the main function, we create an object of demo class named "d1" and then pass this object in PassObj() method, and the value is printed.
Example 2:
C#
// C# program to pass two objects as an argument into method
using System;
class Geeks
{
int num;
// Constructor to initialize the variable value
public Geeks(int val)
{
num = val;
}
public void PassObj(Geeks d1, Geeks d2)
{
// Multiplying the values of both objects
Console.WriteLine(d1.num * d2.num);
}
}
// Driver code
class GFG{
static void Main()
{
// Creating the demo objects
Geeks d1 = new Geeks(6);
Geeks d2 = new Geeks(2);
// Passing 2 objects as arguments to the
// PassObj method and PassObj will print
// the product of the two values in the
// two objects
d1.PassObj(d1, d2);
}
}
Explanation: In the above example, first we create a class named "Geeks" with a constructor to initialize an integer variable. It also has a method named PassObj() which takes two parameters and returns the product of two values. Now in the main function, we create two objects of the Geeks class named "d1" and "d2" and then pass this object in PassObj() method, and the value is printed.
Explore
Introduction
Fundamentals
Control Statements
OOP Concepts
Methods
Arrays
ArrayList
String
Tuple
Indexers