none
Creating a method for another method

    Question

  • Hello,

    I was wondering how can I create a method to use for another method just like this

    myclass.methode1().method();

    Thank you

    Thursday, March 30, 2017 1:02 PM

Answers

  • Don't fully understand what you mean. If methode1() returns a class then you can just call a method on that class.

    For example, if methode1() returned a string you could chain on a call to Trim(), which is a method of String:

    string result = instanceOfmyClass.SomeMethodThatReturnsString().Trim();

    It is quite possible for methode1 to return another (or same) instance of myclass, allowing you to call another method of myclass in a similar way. This is a common pattern with immutable classes.

    For example:

    class PiggyBank
    {
        private readonly int _amount = 0;
        
        public PiggyBack(int initialAmount)
        {
           _amount = initialAmount;
        }
    
    
        public PiggyBank Add(int amountToAdd)
        {
           return new PiggyBank(_amount + amountToAdd);
        }
    
    }

    Then you could add multiple amounts using:

    PiggyBank pb = new PiggyBank(10).Add(15).Add(20);


    • Edited by RJP1973 Thursday, March 30, 2017 1:08 PM
    • Marked as answer by ayman-at1000 Thursday, March 30, 2017 2:00 PM
    Thursday, March 30, 2017 1:08 PM

All replies

  • Don't fully understand what you mean. If methode1() returns a class then you can just call a method on that class.

    For example, if methode1() returned a string you could chain on a call to Trim(), which is a method of String:

    string result = instanceOfmyClass.SomeMethodThatReturnsString().Trim();

    It is quite possible for methode1 to return another (or same) instance of myclass, allowing you to call another method of myclass in a similar way. This is a common pattern with immutable classes.

    For example:

    class PiggyBank
    {
        private readonly int _amount = 0;
        
        public PiggyBack(int initialAmount)
        {
           _amount = initialAmount;
        }
    
    
        public PiggyBank Add(int amountToAdd)
        {
           return new PiggyBank(_amount + amountToAdd);
        }
    
    }

    Then you could add multiple amounts using:

    PiggyBank pb = new PiggyBank(10).Add(15).Add(20);


    • Edited by RJP1973 Thursday, March 30, 2017 1:08 PM
    • Marked as answer by ayman-at1000 Thursday, March 30, 2017 2:00 PM
    Thursday, March 30, 2017 1:08 PM
  • Thank you so much that's what I was looking for
    Thursday, March 30, 2017 2:00 PM