C
C#9mo ago
ABp16

Selecting an overloaded method based on the runtime type of an object by casting it to dynamic

Is this something I should do ? Is it a common pattern ? Are there any downsides / unexpected behavior I can encounter doing this ?
private ResultValue ProcessAstNode(AstNode.Expr.Block node)
{
...
}

private ResultValue ProcessAstNode(AstNode node)
{
// Select the right method depending on the runtime type of node
return ProcessAstNode((dynamic)node);
}
private ResultValue ProcessAstNode(AstNode.Expr.Block node)
{
...
}

private ResultValue ProcessAstNode(AstNode node)
{
// Select the right method depending on the runtime type of node
return ProcessAstNode((dynamic)node);
}
11 Replies
Jimmacle
Jimmacle9mo ago
the downside is throwing away type safety, i'm not even sure this works if it was me i'd explicitly match certain types to the right methods
ABp16
ABp16OP9mo ago
It works !
No description
Jimmacle
Jimmacle9mo ago
gross :KEKW:
ABp16
ABp16OP9mo ago
Why x) I don't quite get why is it throwing away type safety ?
Jimmacle
Jimmacle9mo ago
what if you call this method with a type that doesn't have a method to resolve to? dynamic basically exists to ignore any type checking done by the compiler you shouldn't use it 99% of the time
ABp16
ABp16OP9mo ago
No description
No description
ABp16
ABp16OP9mo ago
I would just use it in this one place
ABp16
ABp16OP9mo ago
this is my actual code
No description
ABp16
ABp16OP9mo ago
I know Body is always an AstNode So there will always be a method to resolve to
ABp16
ABp16OP9mo ago
If it doesn't find a more specific overload it defaults to this one
No description
ABp16
ABp16OP9mo ago
My issue is : - I don't want to put the process methods on the AstNode class itself - I don't want to have to deal with Visitors and what not My options were that or a bunch of node is AstNode.Expr.Block block for all of the subclasses
Want results from more Discord servers?
Add your server