0

I want to be able to do something like that:

var question = new MyClass();
question.Add("SomeString").Call(someFunc);

I already googled and checked out other questions, but I did not found an answer. Sorry if this question already exists, but i did not really no what to search for.

Kirdus
  • 97
  • 2
  • 10

4 Answers4

4

It's called method chain. You need to return your object inside your method like this:

public MyClass Foo() {
  ...
  return this;
}
Ivan Yurchenko
  • 3,762
  • 1
  • 21
  • 35
2

You need what is normally known as method chaining:

public MyClass
{
    public MyClass Add(...)
    {
        // Process input...
        return this;
    }

    public MyClass Call(...)
    {
        // Process input...
        return this;
    }
}

Once your MyClass is defined as above, you can also use a one-liner for your code:

MyClass question = new MyClass().Add("SomeString").Call(someFunc);

The trick is all about using return this at the end of all the methods so that the current instance is being returned and is available for the subsequent calls.

Tommaso Belluzzo
  • 23,232
  • 8
  • 74
  • 98
1

You research fluent interface and method chain. For Example:

class Customer{
     string name;
     string surName;
     public Customer SetName(string _name){
         this.name=_name;
         return this;
     }
     public Customer SetSurname(string _surName){
         this.surName=_surName;
         return this;
     }
}

var customer=new Customer().SetName("Hasan").SetSurname("Jafarov");
Hasan Jafarov
  • 628
  • 6
  • 16
  • 1
    Is this _really_ an answer? You have enough rep for a comment right? – maccettura Jan 30 '18 at 21:09
  • 1
    Your answer fails to explain why it is the solution to the question. All you did was post code and not explain why it does what it has to do. – Rafael Jan 30 '18 at 21:33
1

What you want is called fluent syntax.

The simplest way to achieve this is by returning 'this' in your 'Add' method

public class MyQuestion
{
    public MyQuestion Add(string contentToAdd)
    {
        // Here goes some logic
        return this;
    }
}

If you want to read more: Look at this

Link
  • 1,307
  • 1
  • 11
  • 23