C#: Avoid duplicate code in Extension method When the base class is extended

I have class A and class B inherits Class A.

Class A has extension method. My problem is Class A extension method don’t have all properties, So, I need to create Extension method for class B.

In this case, How can I use Class A extension method and avoid duplicate code in class B extension method.

public class A
{
    public int Id { get; set; }
    public string FirstName {get; set; }
    public string LastName { get; set; }
}

public class B: A
{
    public int Age { get; set; }
}

internal static class ClassAExtension
{
    public static ADto ExtensionA(this A a)
    {
        return a != null
            ? new ADto
            {
                Id = a.Id,
                Name = a.FirstName + " " + a.LastName
            }
            : null;
    }
}

public class ADto
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set;}
}

>Solution :

Use pattern matching.

    public static ADto ExtensionA(this A a)
    {
        if (a is null) return null;

        var result = new ADto {
            Id = a.Id,
            Name = $"{a.FirstName} {a.LastName}"
        };

        if (a is B b) {
            result.Age = b.Age;
        }

        return result;
    }

Leave a Reply