C
C#2y ago
reeeeeee

When to use object or dynamic type

Is there any specific case where those are a " proper way to do it", or is usually better to keep with the actual custom-made objects?
11 Replies
Becquerel
Becquerel2y ago
It is always better to use proper objects dynamic is a relic of the past that should be avoided in new development for things like deserializing JSON, there are tools which can automatically generate proper DTO types
Thinker
Thinker2y ago
As a rule of thumb: Never ever ever ever ever ever ever ever use dynamic
reeeeeee
reeeeeee2y ago
Yeah thought so.. got some old project of a coworker, and there is lots of dynamic/object usage, which I honestly didnt rly use before.. Is there any big difference between those, or are they kinda the same? (object/dynamic)
Becquerel
Becquerel2y ago
using object is slightly better but only slightly dynamic completely turns off all form of type-checking during compilation with object, you can at least use 'is' checks to try and be a bit safer it's still not preferable, though - if you have a method that takes object as an argument, it is usually possible to make it generic instead in case you didn't know, object is what everything in .NET inherits from. so it's still in the type-system, just so vague and abstract it's hard to do anything useful with it safely
Tvde1
Tvde12y ago
I saw one usage of dynamic in production code, and it was to do:
void SomeMethod(MyOneObject x) => ...;
void SomeMethod(MyOtherObject x) => ...;
void SomeMethod(SomeWeirdObject x) => ...;

void GenericMethod<T>
{
T obj = ...;
SomeMethod((dynamic) obj);
}
void SomeMethod(MyOneObject x) => ...;
void SomeMethod(MyOtherObject x) => ...;
void SomeMethod(SomeWeirdObject x) => ...;

void GenericMethod<T>
{
T obj = ...;
SomeMethod((dynamic) obj);
}
Becquerel
Becquerel2y ago
monkaShake worries me
reeeeeee
reeeeeee2y ago
Especially when it comes to readibility, you have to search a lot of parts of the code before you even know what you are working with.. and when you use same code for multiple object types and suddenly random exceptions are coming to the fore
Becquerel
Becquerel2y ago
yyyyyep such is life with legacy codebases
Thinker
Thinker2y ago
I think that's like one of the only actually acceptable-ish uses of it
Tvde1
Tvde12y ago
acceptable-ish, yeah still gives you runtime errors if no overload is found I think
Thinker
Thinker2y ago
I think it'll pick the most specific overload