Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C# Data Types
  • C# Decision Making
  • C# Methods
  • C# Delegates
  • C# Constructors
  • C# Arrays
  • C# ArrayList
  • C# String
  • C# Tuple
  • C# Indexers
  • C# Interface
  • C# Multithreading
  • C# Exception
Open In App
Next Article:
C# | Boolean.CompareTo(Object) Method
Next article icon

C# | Method returning an object

Last Updated : 10 May, 2019
Comments
Improve
Suggest changes
Like Article
Like
Report

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:




// C# program to illustrate the concept
// of the method returning an object
using System;
  
class Example {
  
    // Private data member
    private string str;
  
    // Method to set the value of str
    public void setdata(string s)
    {
        str = s;
    }
  
    // Method to display the value of str
    public void Display()
    {
        Console.WriteLine("String is: " + str);
    }
  
    // Method that return object
    public Example Astr(Example ex)
    {
  
        // Creating object of Example
        Example obj = new Example();
  
        // Adding the value of passed 
        // an object in the current object
        // and adding the sum in another object
        obj.str = str + ex.str;
  
        // Returning the object
        return obj;
    }
}
  
// Driver Class
class GFG {
  
    // Main method
    static void Main()
    {
  
        // Declaring objects of Example
        Example o1 = new Example();
        Example o2 = new Example();
  
        // Initialize the values to the objects
        o1.setdata("Geeks");
        o2.setdata("forGeeks");
  
        // Adding value of both objects
        // and the result will be
        // assigned into third object
        Example o3 = o1.Astr(o2);
  
        // Display the data
        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:




// C# program to illustrate the 
// concept that how method returns 
// an object
using System;
  
class Triangle {
  
    // Data member of class
    int Base;
    int Height;
  
    // Constructor of class
    public Triangle(int b, int h)
    {
        Base = b;
        Height = h;
    }
  
    // Method return area of triangle
    public int Area()
    {
        return ((Base * Height) / 2);
    }
  
    // Method display the dimension of triangle
    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 {
  
    // Main method
    public static void Main()
    {
  
        // Creating and initializing object
        Triangle t1 = new Triangle(2, 8);
  
        // Display the dimensions and area of triangle
        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.



Next Article
C# | Boolean.CompareTo(Object) Method
author
ankita_saini
Improve
Article Tags :
  • C#
  • CSharp-method

Similar Reads

  • C# | Int16.ToString Method | Set - 2
    Int16.ToString Method is used to convert the numeric value of the current instance to its equivalent string representation. There are 4 methods in the overload list of this method as follows: ToString(IFormatProvider) Method ToString(String, IFormatProvider) Method ToString() Method ToString(String)
    2 min read
  • C# | Boolean.CompareTo(Object) Method
    Boolean.CompareTo(Object) Method is used to compare the current instance to a specified object and returns an integer which shows their relationship to one another. Syntax: public int CompareTo (object obj); Here, it takes an object to compare to current instance or null. Return Value: This method r
    2 min read
  • C# | Byte.Equals(Object) Method
    This method is used to get a value which indicates whether the current instance is equal to a specified object or not. Syntax: public override bool Equals (object obj); Here, it takes an object to compare with the current instance or null. Return Value: This method returns true if obj is an instance
    2 min read
  • C# | Object.GetTypeCode() Method with Examples
    This method is used to return the Type of the current instance. Here, Type Represents type declarations i.e. class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types. The System.Object class is
    3 min read
  • C# | Object.GetHashCode() Method with Examples
    This method is used to return the hash code for this instance. A hash code is a numeric value which is used to insert and identify an object in a hash-based collection. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality. Syntax: public virtual int
    2 min read
  • C# | Convert.GetTypeCode(Object) Method
    This method is used to return the TypeCode for the specified object.Syntax: public static TypeCode GetTypeCode (object value); Here, the value is an object that implements the IConvertible interface.Return Value: This method returns the TypeCode for value, or Empty if value is null.Below programs il
    2 min read
  • C# Class and Objects
    Class and Object are the basic concepts of Object-Oriented Programming which revolve around real-life entities. A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member functions which define actions) into a single uni
    5 min read
  • Partial Methods in C#
    C# contains a special method is known as a partial method, which contains declaration part in one partial class and definition part in another partial class or may contain both declaration and definition in the same partial class. Basically, partial methods exist in the partial class, or in the stru
    2 min read
  • C# | Type.GetMethods() Method
    Type.GetMethods() Method is used to get the methods of the current Type. There are 2 methods in the overload list of this method as follows: GetMethods(BindingFlags) Method GetMethods() Method GetMethods(BindingFlags) Method This method is used to search for the methods defined for the current Type,
    5 min read
  • C# | Operator Overloading
    Prerequisite: Operators in C# The concept of overloading a function can also be applied to operators. Operator overloading gives the ability to use the same operator to do various operations. It provides additional capabilities to C# operators when they are applied to user-defined data types. It ena
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences