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?
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.
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.");
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With