Henrik Clausen
Henrik Clausen

Reputation: 729

Class with hierachy of functions

I want to make a class library with a hierachy of functions and properties. In my imagined pesudo code it could be like this:

public class SomethingHandler{
  private string _someGlobalSalt;
  public SomethingHandler(string salt){
    _someGlobalSalt= salt;
  }

  public class NestOfFunctions{
    public string HandleStuff(string input){
        return input + "With" + _someGlobalSalt;
    }
  }
}

And I would consume it like this:

var newHandlerObject = new SomethingHandler("SaltAndPepperOn");
var result = newHandlerObject.NestOfFunctions.HandleStuff("Salad");

Now if this were the way to do it result would contain "SaladWithSaltAndPepperOn".

But I realize that this is NOT the way to do this, since the child classes should be ignorant of the parent class, but how then can I make a group of nested classes with a common property?

Upvotes: 0

Views: 52

Answers (1)

Marco Salerno
Marco Salerno

Reputation: 5203

You can achieve it this way:

class Program
{
    static void Main(string[] args)
    {
        var newHandlerObject = new SomethingHandler.NestOfFunctions("SaltAndPepperOn");
        var result = newHandlerObject.HandleStuff("Salad");
        Console.WriteLine(result);
    }
}

public class SomethingHandler
{
    public class NestOfFunctions
    {
        private string _someGlobalSalt;

        public NestOfFunctions(string salt)
        {
            _someGlobalSalt = salt;
        }
        public string HandleStuff(string input)
        {
            return input + "With" + _someGlobalSalt;
        }
    }
}

The use is:

        var newHandlerObject = new SomethingHandler.NestOfFunctions("SaltAndPepperOn");
        var result = newHandlerObject.HandleStuff("Salad");

OR

        var result = new SomethingHandler.NestOfFunctions("SaltAndPepperOn").HandleStuff("Salad");

Upvotes: 1

Related Questions