Home » .Net

Method returning object in C#

Learn: How to return object through method in C#.Net? This example will explain how a method can return an object?

This example, shows how a method can return object in C#.Net?

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);
		}

		//methdo that will return an object 
		public Sample AddOb(Sample S1)
		{
			//creating object 
			Sample S = new Sample();
			//adding value of passed object in current object
			//and adding sum in another object 
			S.value = value + S1.value;
			//returning object 
			return S;
		}
	}

	//main class containing main method
	class Program
	{
		//main method 
		static void Main()
		{
			//declaring objects 
			Sample S1 = new Sample();
			Sample S2 = new Sample();

			//setting values to the objects
			S1.setValue(10);
			S2.setValue(20);
			
			//adding value of both objects, result will be 
			//assigned in the third object
			Sample S3 = S1.AddOb(S2);
			
			//printing all values
			S1.printValue();
			S2.printValue();
			S3.printValue();
		}
	}
}

Output

Value : 10
Value : 20
Value : 30

In above program, we are creating a user define class named Sample. It contains a data member value. We create method AddOb(), it returns sum of current object and passed object into this method. Here, AddOb() method is returning the object.






Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL




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


© https://www.includehelp.com some rights reserved.