Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading