An example of using the dynamic keyword in C# .NET

The dynamic keyword in C# is similar to Reflection. It helps you deal with cases where you’re not sure of the concrete type of an object. However, you may expect the object to have a certain method that you can invoke at runtime. E.g. you have a framework that external users can write plugins for. You may set up a list of rules for the plugin to be valid, e.g. it must have a method called “Execute” and a property called “Visible”.

There are various ways you can solve this problem and one of them is dynamic objects. Using the dynamic keyword will turn off the automatic type checking when C# code is compiled. The validity of the code will only be checked at runtime.

Let’s model the problem outlined in the first paragraph in code. Say an external user wrote a plugin which implements the required elements as follows:

public class MyBrilliantPlugin
{
	public void Execute()
	{
		Console.WriteLine("The plugin is executing...");
	}

	public bool Visible
	{
		get
		{
			return true;
		}
	}
}

Then the plugin is loaded to your framework but you won’t of course know in advance its exact type. However, you’ll be able to see its name therefore you can load it to the assembly. Say that all plugins need to be saved in a certain folder called Plugins and the full file path to MyBrilliantPlugin.dll is c:\plugins\MyBrilliantPlugin.dll:

Type pluginType = Assembly.LoadFrom(@"c:\plugins\MyBrilliantPlugin.dll").GetType("MyBrilliantPlugin.MyBrilliantPlugin");
dynamic plugin = Activator.CreateInstance(pluginType);

MyBrilliantPlugin.MyBrilliantPlugin is the fully qualified name of the plugin. In this case I put a class called MyBrilliantPlugin within a C# class library called MyBrilliantPlugin hence the full name of MyBrilliantPlugin.MyBrilliantPlugin.

GetType will return a Type. We’ll call Activator to create an instance of that type. However, CreateInstance returns an object and not the statically typed object MyBrilliantPlugin. Note how you can declare it as “dynamic”. You can in fact declare any type of object as dynamic. It essentially means that we don’t know the exact type of the plugin but we ask the compiler not to care.

You can then call any expected method on it but you won’t of course get compile time checking or intellisense to find the members of the invoked object. Here’s an example how you can invoke the plugin:

try
{
	Console.WriteLine("About to execute plugin...");
	plugin.Execute();
	Console.WriteLine("Is plugin visible: {0}", plugin.Visible);
}
catch (Exception ex)
{
	Console.WriteLine("Ooops...: {0}", ex.Message);
}

Just to repeat: the compiler won’t check for you at compile time whether there’s a method called Execute() and a property called Visible on the dynamic object. You type “plugin.” there won’t be any IntelliSense helping you out. You’ll get an exception if the invoked elements are not found at runtime.

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

iReadable { }

.NET Tips & Tricks

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: