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?

2 answers

  • answered 2017-10-11 10:13 Qklanski

    You should pass parent's reference to the nested class, f.e. by constructor. See example:

    public class Container
    {
        public class Nested
        {
            private Container parent;
    
            public Nested()
            {
            }
            public Nested(Container parent)
            {
                this.parent = parent;
            }
        }
    }
    

    Read also: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/nested-types

  • answered 2017-10-11 10:13 Marco Salerno

    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");