Sadistik
Sadistik

Reputation: 135

Class method building

I did this kind of class in the past and I can't remember exactly how..

Say you have this class :

public class TestMethod
{
    private string a, b, c, d, e;

    public void SetA(string text) => a = text;
    public void SetB(string text) => b = text;
    public void SetC(string text) => c = text;
    public void SetD(string text) => d = text;
    public void SetE(string text) => e = text;

    public void Print()
    {
        Console.WriteLine(string.Format("A: {0}\nB: {1}\nC: {2}\nD: {3}\nE: {4}\n", a,b,c,d,e));
    }
}

And you would like to call it like so:

TestMethod method = new TestMethod();
method.SetA("").SetB("").Print();

What do I need to add to my class and what is this called ?

Upvotes: 2

Views: 57

Answers (1)

rokkerboci
rokkerboci

Reputation: 1167

This is called a call-chain. You have to add a return this statement.

public class TestMethod
{
    private string a, b, c, d, e;

    public TestMethod SetA(string text) { a = text; return this; }
    public TestMethod SetB(string text) { b = text; return this; }
    public TestMethod SetC(string text) { c = text; return this; }
    public TestMethod SetD(string text) { d = text; return this; }
    public TestMethod SetE(string text) { e = text; return this; }

    public void Print()
    {
        Console.WriteLine(string.Format("A: {0}\nB: {1}\nC: {2}\nD: {3}\nE: {4}\n", a,b,c,d,e));
    }
}

Upvotes: 6

Related Questions