2

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?

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
csLijo
  • 481
  • 2
  • 8
  • 26

3 Answers3

5

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.

Peter Porfy
  • 8,921
  • 3
  • 31
  • 41
5

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.");
        }
    }
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
1

You have to return the Object itself to chain such method calls like this

public Class1 Add(Object Whatever)
{
    // Do code here
    return this;
}
boindiil
  • 5,805
  • 1
  • 28
  • 31