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.

Consider the following Dog class:

public class Dog
	public string Name { get; }
	public string Type { get;}
	public int Age { get; }

	public Dog(string name, string type, int age)
		Name = name;
		Type = type;
		Age = age;

If you declare a new Dog as a dynamic type and start typing…:

dynamic dynamicDog = new Dog("Fiffi", "Terrier", 3);

…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:

dynamic dynamicDog = new Dog("Fiffi", "Terrier", 3);
Dog convertedDog = dynamicDog;

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…:

public class Dog : IConvertible
//code omitted
        public int ToInt32(IFormatProvider provider)
		return Age;
//rest of IConvertible interface functions throw not implemented exception

…then we can convert a dynamic type to an integer:

int integerDog = Convert.ToInt32(dynamicDog);

integerDog will be 3 as expected.

View all posts on Reflection here.


About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog


Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: