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#
using System;
class demo
{
int value;
public demo( int val)
{
value = val;
}
public void PassObj(demo d2)
{
Console.WriteLine(d2.value);
}
}
class GFG{
static void Main()
{
demo d1 = new demo(6);
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#
using System;
class Geeks
{
int num;
public Geeks( int val)
{
num = val;
}
public void PassObj(Geeks d1, Geeks d2)
{
Console.WriteLine(d1.num * d2.num);
}
}
class GFG{
static void Main()
{
Geeks d1 = new Geeks(6);
Geeks d2 = new Geeks(2);
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.
Share your thoughts in the comments
Please Login to comment...