Q:

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

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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
			S1.setValue(10);
			S2.setValue(20);
			
			//passing objects 
			S3.AddOb(S1, S2);
			//printing the objects
			S1.printValue();
			S2.printValue();
			S3.printValue();
		}
	}
}

Output

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.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C# Basic Programs | Class, Object, Methods

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Method returning object in C#... >>
<< How to call non-trailing arguments as default argu...