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);
dynamicDog.

…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;
Console.WriteLine(convertedDog.Name);

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.

Advertisements

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:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s

ultimatemindsettoday

A great WordPress.com site

Elliot Balynn's Blog

A directory of wonderful thoughts

Robin Sedlaczek's Blog

Developer on Microsoft Technologies

HarsH ReaLiTy

A Good Blog is Hard to Find

Softwarearchitektur in der Praxis

Wissenswertes zu Webentwicklung, Domain-Driven Design und Microservices

the software architecture

thoughts, ideas, diagrams,enterprise code, design pattern , solution designs

Technology Talks

on Microsoft technologies, Web, Android and others

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

Anything around ASP.NET MVC,WEB API, WCF, Entity Framework & AngularJS

Cyber Matters

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

Guru N Guns's

OneSolution To dOTnET.

Johnny Zraiby

Measuring programming progress by lines of code is like measuring aircraft building progress by weight.

%d bloggers like this: