Search code examples
c#object-composition

Is there Method Inheritance in C#


I am wondering whether there is any feature like method inheritance rather than whole class inheritance, let me elaborate what I am trying to explain :

class a {
   public void GetA(){
     // some logic here
}
}

class b {
    public void GetB() : new Class().GetA()
}

I know it looks weird but I was reading how to do delegation in object composition pattern and I thought this pattern for some reason.


Solution

  • If you just want to call GetA() inside of GetB(), but don't want to define or explicitly reference an instance of class a in GetB(), you can pass GetA() in as a delegate.

    In C#, there are many predefined delegates such as Action and Func. Or, you could always roll your own delegate to match the method signature.

        class a
        {
            public void GetA()
            {
                Console.WriteLine("Hello World!");
            }
        }
    
        class b
        {
            // No explicit reference to class a of any kind.
            public void GetB(Action action)
            {
                action();
            }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var a = new a();
                var b = new b();
    
                b.GetB(a.GetA);
            }
        }