Lions Kao Lions Kao - 20 days ago 6
C# Question

How can i create infinite property

In the C# , string has infinite property like this

string a = "";
a.ToString().Length.ToUpper().ToLower().ToString()....


and how can i create like this

ClassName a = new ClassName();
a.text("message").title("hello").icon("user");

Answer

Every one of those methods on string simply return a string. (Well, almost. You have a .Length in there which isn't correct.) If you return your object from your methods, you can achieve the same concept. (In some cases this can be referred to as a "fluent syntax", though the string example isn't necessarily really that.)

For example, say your .Title() method is as such:

class ClassName
{
    //...

    public ClassName Title(string title)
    {
        this.Title = title;
        return this;
    }
}

Then any time you call someObj.Title("some string") that method will return the object itself:

var someObj = new ClassName();
someObj.Title("some title").SomeOtherOperation();

It's not "infinite", it's just a method that returns the same type on which it's invoked. It can return itself or any instance of that type. Just be sure to pay attention to the interface you're building when you do this, because you could accidentally create fairly unintuitive things. (Fluent chains which produce unintended side-effects on the original object or don't produce intended effects on the original object.)

Comments