Convert a dynamic type to a concrete object in .NET C#

Dynamic objects in C# let us work with objects without compile time error checking in .NET. They are instead checked during execution. As a consequence we can’t use IntelliSense while writing the code to see what properties and functions an object has.

…in Visual Studio then you won’t get any help from IntelliSense as to which public elements a Dog has. However, if you know the exact type of a dynamic object then it’s perfectly fine to convert it to that concrete type and get access to its public members:

We didn’t even have to use an explicit cast here. As long as the dynamic object can be implicitly cast to a concrete object then the above code will work. However, if we try to convert a Dog to an integer…:

int integerDog = dynamicDog;

…then we’ll get a RuntimeBinderException when executing the code with the message “Additional information: Cannot implicitly convert type ‘Various.Objects.Dog’ to ‘int’ “. The above code won’t generate any compile error since dynamic code is a runtime feature. The compiler has no way of knowing if this particular code snippet will be legal during execution time.

However, if we let Dog implement the IConvertible interface where we only specify the ToInt32 function…: