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?
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();
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With