I am trying to write a DSL
I have methods that return strings but if I want to combine the strings I need to use a + symbol but I would like to call the methods together but I'm unsure how to achieve it
I have methods at the moment such as
MyStaticClass.Root() MyStaticClass.And() MyStaticClass.AnyInt()
which return strings
I would like to be able to do
Root().And().AnyInt()
which result in a string
The methods should return a wrapper class. The methods are also instance methods of the wrapper class. Example:
class Fluent
{
private string _value;
public Fluent And()
{
this._value += "whatever";
return this;
}
public Fluent AnyInt()
{
this._value += "42";
return this;
}
public override string ToString() { return _value; }
}
You could also define an implicit or explicit conversion from Fluent
to string, rather than (or in addition to) the ToString()
override.
Also, for production code, I'd use a string builder to avoid many calls to Concat
.