Inheritance of C# functions and using reusability

I’m drawing a complete blank on what to actually 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");
    }
}

What I want to do though is get rid of the code duplication, changing the interface into something appropriate like maybe a class, but then use 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();
});

And 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.

4

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 {}

4

(Note: This answer assumes that you want to actually have different implementations of Draw() for the derived classes. If you do not need to do that then you can use one of the other answers to your question!)

You can introduce an intermediary abstract base class which implements the functionality:

public interface IShapes
{
    public void Draw();
}

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

public class Square : ShapesBase
{
    public override void Draw()
    {
        base.Draw();
    }
}

public class Circle : ShapesBase
{
    public override void Draw()
    {
        base.Draw();
    }
}

Note that if you override the Draw() method you MUST remember to still call the base method otherwise you won’t get the desired output (I assume that your concrete classes will generally want to implement Draw().

If you omit the Draw() implementations from the concrete classes altogether it will still work:

public interface IShapes
{
    public void Draw();
}

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

public class Square : ShapesBase
{
}

public class Circle : ShapesBase
{
}

But generally you would be overriding the virtual methods.


Incidentally, if you want to force the derived classes to implement some kind of Draw() method you can take a different approach. You can introduce an abstract DrawImpl() method which the derived classes must implement, and which is called from the abstract base class’s concrete implementation of Draw().

This approach does also have the advantage that the derived classes don’t need remember to call the base class version:

public interface IShapes
{
    public void Draw();
}

public abstract class ShapesBase : IShapes
{
    protected abstract void DrawCore();

    public void Draw()
    {
        Console.WriteLine(GetType().FullName?.Substring(GetType().FullName.IndexOf('.') + 1) + " - Draw");
        DrawCore();
    }
}

public class Square : ShapesBase
{
    protected override void DrawCore()
    {
        Console.WriteLine("Square.DrawCore()");
    }
}

public class Circle : ShapesBase
{
    protected override void DrawCore()
    {
        Console.WriteLine("Circle.DrawCore()");
    }
}

This approach also works if you want to make overriding the DrawCore() method optional, but still get the desired output, simply by declaring DrawCore() as virtual instead of abstract:

public interface IShapes
{
    public void Draw();
}

public abstract class ShapesBase : IShapes
{
    protected virtual void DrawCore()
    {
        // Do nothing.
    }

    public void Draw()
    {
        Console.WriteLine(GetType().FullName?.Substring(GetType().FullName.IndexOf('.') + 1) + " - Draw");
        DrawCore();
    }
}

public class Square : ShapesBase
{
}

public class Circle : ShapesBase
{
}

This could be useful if only some of the derived classes need to override DrawCore().

0

Use a generic extension method. This also allows you to use typeof<T> instead of this.GetType() which resolves at compile-time. Also, I’m pretty sure you can just use Name (instead of parsing FullName) which provides the unqualified name.

static class ShapeExtensions
{
    static void Draw<T>(this T shape) where T : IShapes
    {
        Console.WriteLine(typeof(T).Name + " - Draw");
    }
}

Note that typeof(T) will only give you the type of the variable (which is determined at compile time), not the instance (which is determined at runtime). So if you have a List<IShapes> it will always print IShapes - Draw. If you want the runtime type of the instance you can still use GetType().

static void Draw<T>(this T shape) where T : IShapes
{
    Console.WriteLine(shape.GetType().Name + " - Draw");
}

You call it exactly the same way.

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

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật