Returning 'this' in a static method
-
31-05-2021 - |
Question
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?
Solution
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();
OTHER TIPS
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()
I'm surprised the language even allows this - the methods you've defined clearly return an instance, but in the very same class definition, you've declared that you can't ever create instances of it.
You can still define static methods on a normal class. You can force implementers to always use the fluent interface and not instantiate MyClass
themselves by:
- Giving MyClass a private constructor
private MyClass()
that can only be called from insideMyClass
- marking MyClass as
sealed
to prevent creation of inheritors that expose a public constructor.
You cannot use 'this' keyword in static method, because 'this' returns CURRENT INSTANCE of class. But static methods doesn't belong to any instance (instead, they belong to class itself) and thus cannot return it.
Why do you need your class and methods to be static? Removing all static keywords will make it work. If you , use Singleton pattern instead.