© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•3y ago•
2 replies
UltraWelfare

Simplifying creation of inherited classes

class Entity {
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public string Field3 { get; set; }
    public int? FieldA { get; set; }
    public int? FieldB { get; set; }

}

class Base {
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public string Field3 { get; set; }
}

class A : Base {
    public int FieldA { get; set; }
}

class B : Base {
    public int FieldB { get; set; }
}
class Entity {
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public string Field3 { get; set; }
    public int? FieldA { get; set; }
    public int? FieldB { get; set; }

}

class Base {
    public string Field1 { get; set; }
    public string Field2 { get; set; }
    public string Field3 { get; set; }
}

class A : Base {
    public int FieldA { get; set; }
}

class B : Base {
    public int FieldB { get; set; }
}


Entity entity = GetEntityFromDatabase();
if (entity.Field1 == "A") {
    return new A {
        Field1 = entity.Field1,
        Field2 = entity.Field2,
        Field3 = entity.Field3,
        FieldA = entity.FieldA.Value
    };
} else if (entity.Field2 == "B") {
    return new B {
        Field1 = entity.Field1,
        Field2 = entity.Field2,
        Field3 = entity.Field3,
        FieldB = entity.FieldB.Value
    };
}
Entity entity = GetEntityFromDatabase();
if (entity.Field1 == "A") {
    return new A {
        Field1 = entity.Field1,
        Field2 = entity.Field2,
        Field3 = entity.Field3,
        FieldA = entity.FieldA.Value
    };
} else if (entity.Field2 == "B") {
    return new B {
        Field1 = entity.Field1,
        Field2 = entity.Field2,
        Field3 = entity.Field3,
        FieldB = entity.FieldB.Value
    };
}


Basically we need to fetch Entity from the database and then map it into A or B depending on a field.

That means you'll have to repeat the field copies a lot. With more fields and more "A"-"B"-"C"-"D"s... this will become a nightmare to maintain. Any other ideas?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ List of inherited objects
C#CC# / help
3y ago
❔ Getting Inherited Generic-Typed Inner Classes With Reflection
C#CC# / help
3y ago
How to share instance of an object in base class to its inherited classes?
C#CC# / help
3y ago
✅ Make set accessor of inherited prop private
C#CC# / help
4y ago