Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call method().method() in C# [duplicate]

Tags:

c#

Possible Duplicate:
Method-Chaining in C#
creating API that is fluent

How can I do the below coding?

Class1 objClass1 = new Class1().Add(1).Add(2).Add(3)...

and so on..

How can I implement the Add() method to call infinite time that will reflect on same object?

like image 658
csLijo Avatar asked May 23 '26 13:05

csLijo


2 Answers

Logically, if you want to use the same object after the call then you must return that object, which is referred with this in the method.

class Class1
{
    public Class1 Add(int num)
    {
        //TODO
        return this;
    }
}

This is a case of method-chaining.

like image 70
Peter Porfy Avatar answered May 26 '26 20:05

Peter Porfy


It is called chainable methods.

Method chaining, also known as named parameter idiom, is a common technique for invoking multiple method calls in object-oriented programming languages. Each method returns an object (possibly the current object itself), allowing the calls to be chained together in a single statement.

Basicly, your method should return a current instance of your object.

public YourClass Add()
{
    return this;
}

For a clean understanding of method chaining, here is the code converted from Java include in wikipedia page. The the setters return "this" (the current Person object).

using System;

namespace ProgramConsole
{
    public class Program
    {
        public static void Main(string[] args)
        {
            Person person = new Person();
            // Output: Hello, my name is Soner and I am 24 years old.
            person.setName("Soner").setAge(24).introduce();
        }
    }

    class Person
    {
        private String name;
        private int age;

        public Person setName(String name)
        {
            this.name = name;
            return this;
        }

        public Person setAge(int age)
        {
            this.age = age;
            return this;
        }

        public void introduce() {
                Console.WriteLine("Hello, my name is " + name + " and I am " + age + " years old.");
        }
    }
}
like image 42
Soner Gönül Avatar answered May 26 '26 19:05

Soner Gönül