C
C#3y ago
MaggyD

Achieving polymorphism for an association

Hi, I'm curious about the nature of run-time/compile-time polymorphism when a parent object is associated with some other object. What I mean by association is that an object keeps that parent class as a reference, i.e., it owns it. What I'm trying to figure out right now in my application is how can I associate children of the parent in substitution for the parent class, yet some how gain access to child specific attributes and methods. Is this possible? Examples:
public class ContainerClass {

private ParentClass _parent;

public ContainerClass(ParentClass parentClass) {
_parent = parentClass;
}

}

public class ParentClass {
...
}

public class ChildClassOne : ParentClass {

}

public class ChildClassTwo : ParentClass {

}
public class ContainerClass {

private ParentClass _parent;

public ContainerClass(ParentClass parentClass) {
_parent = parentClass;
}

}

public class ParentClass {
...
}

public class ChildClassOne : ParentClass {

}

public class ChildClassTwo : ParentClass {

}
2 Replies
becquerel
becquerel3y ago
The code snippet you've posted should compile are you asking if it's possible to treat _parent as one of the child classes? if so you probably want the is keyword
if (_parent is ChildClassOne one)
{
one.MethodOnlyOnChildClass();
}
if (_parent is ChildClassOne one)
{
one.MethodOnlyOnChildClass();
}
this will check if the runtime instance is assignable to the child class, and if so, give you a new variable (one) that you can access the child-specific methods and properties on however, i would suggest that if you're frequently checking if something is a child class, you're probably missing more elegant ways to do polymorphism
MaggyD
MaggyDOP3y ago
Ok, that's why I'm here I want to find a more elegant way Essentially, I have a real challenge on my hands... we have an API that works on a base class, but now we are extended such api so that it works on two sub classes that share some common parent class However, I often find myself looking into and casting because we are using Ardalis specifications, so I need to ask in a specification, ok return this property Include this property that only exists on that sub class, therefor, I need to do bunch of casting or just write different specifications, classes, and functions to work on these subclasses This would all be much simpler if c# supported union types I unfortunately cannot do something like this
var templates = templateType switch
{
TemplateType.Letter => await _templateHistoryRepository.ListAsync(new AllLetterReusableBlocksSpec())
TemplateType.Email => await _templateHistoryRepository.ListAsync(new AllEmailReusableBlocksSpec())
};
var templates = templateType switch
{
TemplateType.Letter => await _templateHistoryRepository.ListAsync(new AllLetterReusableBlocksSpec())
TemplateType.Email => await _templateHistoryRepository.ListAsync(new AllEmailReusableBlocksSpec())
};

Did you find this page helpful?