Returning 'this' in a static method

Jon picture Jon · Apr 15, 2012 · Viewed 8.7k times · Source

I would like to make a static class with a fluent interface but I am getting the error:

'this' is not valid in a static property, method ...

Here is my code:

public static MyClass
{
    private static StringBuilder builder;
    private static StringBuilder RouteBuilder
    {
        get
        {
            if (builder == null)
                builder = new StringBuilder();

            return builder;
        }
    }

    public static MyClass Root()
    {
      RouteBuilder.Append("/");
      return this;
    }

    public static MyClass And()
    {
      RouteBuilder.Append("and");
      return this;
    }

    public static MyClass Something()
    {
       RouteBuilder.Append("something");
       return this;
    }
}

This enables me to do MyClass.Root().And().Something();

Is there a way to do this or a workaround?

Answer

Darin Dimitrov picture Darin Dimitrov · Apr 15, 2012

That's not possible. You cannot have an instance of a static class. Since you have marked MyClass as static there cannot be any instances. Don't make it static:

public class MyClass
{
    private StringBuilder builder;
    private StringBuilder RouteBuilder
    {
        get
        {
            if (builder == null)
                builder = new StringBuilder();

            return builder;
        }
    }

    public MyClass Root()
    {
        RouteBuilder.Append("/");
        return this;
    }

    public MyClass And()
    {
        RouteBuilder.Append("and");
        return this;
    }

    public MyClass Something()
    {
        RouteBuilder.Append("something");
        return this;
    }
}

and then you could chain:

var result = new MyClass().Root().And().Something();