VOOZH about

URL: https://www.geeksforgeeks.org/c-sharp/how-to-pass-an-object-as-an-argument-into-method-in-c-sharp/

⇱ How to Pass an Object as an Argument into Method in C#? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Pass an Object as an Argument into Method in C#?

Last Updated : 6 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:


Output
6

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:


Output
12

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.

Comment
Article Tags:
Article Tags:

Explore