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
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
As a rule of thumb:
Never ever ever ever ever ever ever ever use
dynamic
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)
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 safelyI saw one usage of
dynamic
in production code, and it was to do:
worries me
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
yyyyyep
such is life with legacy codebases
I think that's like one of the only actually acceptable-ish uses of it
acceptable-ish, yeah
still gives you runtime errors if no overload is found I think
I think it'll pick the most specific overload