C#
C#

help

Root Question Message

reeeeeee
reeeeeee9/20/2022
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?
Becquerel
Becquerel9/20/2022
It is always better to use proper objects
Becquerel
Becquerel9/20/2022
dynamic is a relic of the past that should be avoided in new development
Becquerel
Becquerel9/20/2022
for things like deserializing JSON, there are tools which can automatically generate proper DTO types
thinker227
thinker2279/20/2022
As a rule of thumb:
Never ever ever ever ever ever ever ever use dynamic
reeeeeee
reeeeeee9/20/2022
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..
reeeeeee
reeeeeee9/20/2022
Is there any big difference between those, or are they kinda the same? (object/dynamic)
Becquerel
Becquerel9/20/2022
using object is slightly better
Becquerel
Becquerel9/20/2022
but only slightly
Becquerel
Becquerel9/20/2022
dynamic completely turns off all form of type-checking during compilation
Becquerel
Becquerel9/20/2022
with object, you can at least use 'is' checks to try and be a bit safer
Becquerel
Becquerel9/20/2022
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
Becquerel
Becquerel9/20/2022
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
Tvde19/20/2022
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);
}
Becquerel
Becquerel9/20/2022
:monkaShake:
Becquerel
Becquerel9/20/2022
that worries me
reeeeeee
reeeeeee9/20/2022
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
Becquerel9/20/2022
yyyyyep
Becquerel
Becquerel9/20/2022
such is life with legacy codebases
thinker227
thinker2279/20/2022
I think that's like one of the only actually acceptable-ish uses of it
Tvde1
Tvde19/20/2022
acceptable-ish, yeah
Tvde1
Tvde19/20/2022
still gives you runtime errors if no overload is found I think
thinker227
thinker2279/20/2022
I think it'll pick the most specific overload
ContactFrequently Asked QuestionsJoin The DiscordBugs & Feature RequestsTerms & Privacy