C# | Method returning an object
In C#, a method can return any type of data including objects. In other words, methods are allowed to return objects without any compile time error.
Example 1:
using System;
class Example {
private string str;
public void setdata( string s)
{
str = s;
}
public void Display()
{
Console.WriteLine( "String is: " + str);
}
public Example Astr(Example ex)
{
Example obj = new Example();
obj.str = str + ex.str;
return obj;
}
}
class GFG {
static void Main()
{
Example o1 = new Example();
Example o2 = new Example();
o1.setdata( "Geeks" );
o2.setdata( "forGeeks" );
Example o3 = o1.Astr(o2);
o1.Display();
o2.Display();
o3.Display();
}
}
|
Output:
String is: Geeks
String is: forGeeks
String is: GeeksforGeeks
Explanation: In the above example, we have a class named as Example. Example class contains setdata() method which is used to set the value of str, and Display() method is used to display the value of str, and Astr() is used to add the value of passed object in current object and adding the sum in another object. In Main method, three objects o1, o2, and o3 of Example class are created. In this statement, Example o3 = o1.Astr(o2);, the value of o1 and o2 object is added and the result is assigned into o3 object.
Example 2:
using System;
class Triangle {
int Base;
int Height;
public Triangle( int b, int h)
{
Base = b;
Height = h;
}
public int Area()
{
return ((Base * Height) / 2);
}
public void Display()
{
Console.WriteLine( "\nBase of the triangle is: "
+ Base + "\nHeight of the triangle is: "
+ Height);
}
public Triangle newdimension( int d)
{
return new Triangle(Base * d, Height * d);
}
}
class GFG {
public static void Main()
{
Triangle t1 = new Triangle(2, 8);
Console.Write( "Dimensions of Triangle is: " );
t1.Display();
Console.Write( "Area of Triangle is: {0}" , t1.Area());
Console.WriteLine();
Console.WriteLine();
Triangle t2 = t1.newdimension(2);
Console.Write( "New Dimensions of Triangle is: " );
t2.Display();
Console.Write( "New area of Triangle is: {0}" , t2.Area());
}
}
|
Output:
Dimensions of Triangle is:
Base of the triangle is: 2
Height of the triangle is: 8
Area of Triangle is: 8
New Dimensions of Triangle is:
Base of the triangle is: 4
Height of the triangle is: 16
New area of Triangle is: 32
Explanation: In the above example, we have a class named as the Triangle. The Triangle class contains constructor Triangle(), method Area() to find the area of the triangle, method Display() to display the dimension of the triangle, and method newdimension() to provide a new dimension of the triangle. The value of the dimension is returned by the object. Now in the Main method there are two objects named as t1 and t2. In this statement Triangle t2 = t1.newdimension(2);, the previous dimension, i.e. 2 and 8 of the triangle is enlarged by 2 and the result assigned to the t2 object.
Last Updated :
10 May, 2019
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...