Home > Blockchain >  How to write fluent methods for a type in C#
How to write fluent methods for a type in C#

Time:03-20

I understand extension methods are a style of programming that lets us invoke different methods of the same type without having to create a new instance of that type. I have used this method several times in Android Java, I do Xamarin Android applications development and most of the times when I want to create an AlertDialog, I would need a builder class which is encapsulated in the same like below

//import the dependency
using AndroidX.AppCompat.App;

//create an instance of an alert dialog
new AlertDialog.Builder(this).SetTitle("Mytitle").SetMessage("This is my message!").Show();

Now suppose I have a similar class like that in my own custom code, How do I define methods that behave the same way, I also noticed that after you call the method new ...Builder.Show(), you are not alowed by the compiler to add more extension methods, How do i achieve that please? Here is my code

class Builder{
//defining the class variables
Context ctx;
string title, message;
public Builder(Context context){
     this.ctx=context;
    }
 //how do i write extension methods such as setMessage and setTitle
void SetTitle(string title){
   this.title=title;
    }
void SetMessage(string message){
   this.message=message;
  }
//define a method for showing the builder, which when after invoked, the
//other two methods cannot be allowed to be invoked
void show(){
 //display the builder
 }

}

I am trying to understand how such programming behavior is achievable, and also learn, Thank You.

CodePudding user response:

These are not extension methods. What you're talking about is fluent methods. To achieve this you just need to make each method return the object it's called on so that you can then chain other fluent methods after that one.

class Builder
{
    //defining the class variables
    Context ctx;
    string title, message;

    public Builder(Context context)
    {
        this.ctx=context;
    }

    public Builder SetTitle(string title)
    {
        this.title=title;
        return this;
    }

    public Builder SetMessage(string message)
    {
        this.message=message;
        return this;
    }
    
    public void Show()
    {
    }
}
  • Related