C# Inheritance – How to Use and Reuse Functions Effectively

c++inheritance

I'm drawing a complete blank on what to call what I want to do (hence the difficulty I am having in trying to research it). But what I do have is this:

public interface IShapes
{
    public void Draw();
}
public class Square : IShapes
{
    public void Draw()
    {
        Console.WriteLine(GetType().FullName?.Substring(GetType().FullName.IndexOf('.') + 1) + " - Draw");
    }
}
public class Circle : IShapes
{
    public void Draw()
    {
    Console.WriteLine(GetType().FullName?.Substring(GetType().FullName.IndexOf('.')+1) + " - Draw");
    }
}

I want to get rid of the code duplication, changing the interface into something appropriate like maybe a class, but then using reflection to call the correct (i.e., the 'most' child inheritance) Draw method.

So elsewhere I could have a call like (to follow the code sample above):

var shapes = new List<IShapes>();
shapes.Add(new Circle());
shapes.Add(new Square());

shapes.ForEach((s) => 
{
s.Draw();
});

This would result in a 'Circle – Draw' and a 'Square – Draw'

I have tried changing the interface into a class (and an abstract) but I feel like I am missing something obvious.

I have also tried, in the Square and Circle : Shapes classes to define public new void Draw() methods that call base.Draw() directly but that doesn't seem to work either.

Best Answer

Depending on your target framework, "default interface methods" might be your friend:

using System;
public interface IShapes
{
    public void Draw()
    {
    
    Console.WriteLine(GetType().FullName?.Substring(GetType().FullName.IndexOf('.') + 1) + " - Draw");
    }
}
public class Square : IShapes {}
public class Circle : IShapes {}