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?

1
  • 3
    Use return this; and your method must have return type Class1 Commented Jan 7, 2013 at 9:26

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Another name for this design style is a fluent interface.
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."); } } } 

1 Comment

Nice explanation for a novice like me.
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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.