-3

I would like to know if I can call methods or function unorderly.

For example like this :

public static class Employee
{
    int s=0;

    public int addOne()
    {
        return s++ ;
    }
}

And now What i need to do:

int sum = Employee.addOne()
                  .addOne()
                  .addOne();
           

1 Answers1

3

Chaining calls (also called a "fluent syntax" or "fluent interface") is not uncommon in C#: in fact, LINQ, an important part of .NET library, can be accessed using fluent syntax. It requires a different method signature: rather than returning an int, you need to return Employee. Here is an example:

public class Employee // You cannot do this with a static class
{
    public int S {get; private set;}

    public Employee addOne()
    {
        S++ ;
        return this;
    }
}

Obviously, you would need to set up some alternative way of accessing the value of s, so the call would look like this:

var employee = new Employee();
int sum = employee.addOne()
              .addOne()
              .addOne()
              .S; // <<== Here is the change
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523