Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning 'this' in a static method

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?

like image 965
Jon Avatar asked Aug 30 '26 20:08

Jon


2 Answers

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();
like image 173
Darin Dimitrov Avatar answered Sep 02 '26 11:09

Darin Dimitrov


return RouteBuilder will make the trick !

EDIT : wrong, sorry

For these cases, you can also just do an Extension class

Say

 public static class StringBuilderExtensions {

    public static StringBuilder Root(this StringBuilder builder) {
      Asserts.IsNotNull(builder);
     builder.Append("/");
     return builder;
    }

   public static StringBuilder And(this StringBuilder builder) {
     Asserts.IsNotNull(builder);
     builder.Append("and");
     return builder;
   }
   //...etc
 }

and use it like

var builder = new StringBuilder();
builder.Root().Append()
like image 36
Raphaël Althaus Avatar answered Sep 02 '26 11:09

Raphaël Althaus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!