How to pass object as argument into method in C#?

Learn: How to pass object as argument into method in C#.Net, in this example, we will be passing object in method.

As we know that we can pass primitive (basic) data types in methods as arguments. Similarly, we can pass objects in methods too.

Here is an example that will accept objects as arguments in the methods.

Consider the example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
	class Sample
		//private data member
		private int value;

		//method to set value
		public void setValue(int v)
			value = v;

		//method to print value
		public void printValue()
			Console.WriteLine("Value : "+value);
		//method to add both objects, here we are passing
		//S1 and S2 which are objects of Sample class
		public void AddOb(Sample S1, Sample S2)
			//adding the value of S1 and S2, 
			//assigning sum in value of current object 
			value = S1.value + S2.value;

	class Program
		static void Main()
			//objects creation
			Sample S1 = new Sample();
			Sample S2 = new Sample();
			Sample S3 = new Sample();
			//passing integers
			//passing objects 
			S3.AddOb(S1, S2);
			//printing the objects


Value : 10
Value : 20
Value : 30

In this example, there is a class Sample, which has value as private data member, here we are providing integer values to data members of S1 and S2 class. Method AddOb() is taking two arguments of Sample (which is class name) and S1 and S2 (which defining the method) are objects.

C# Basic Programs »


Comments and Discussions!

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.