Caleb Jares
Caleb Jares

Reputation: 6307

Pass a C# dynamic object to a method that takes an IDictionary

Right now, I'm doing this

var data = new JobDataMap(new Dictionary<string,string> { {"obj", "stringify"} });

But I want to do this:

dynamic d = new { obj = "stringify" };
var data = new JobDataMap(d);

Is there some secret syntactical sugar that would allow me to do this?

Upvotes: 0

Views: 381

Answers (1)

Kenneth
Kenneth

Reputation: 28737

There's no magical way of doing this. There's no way the compiler can know that your Dynamic object really is a Dictionary at compile time.

That being said, you could create an extension method that converts it to a Dictionary so that you could do something like this:

dynamic d = new { obj = "stringify" };
var data = new JobDataMap(d.ToDictionary());

This blogpost offers an example: http://blog.andreloker.de/post/2008/05/03/Anonymous-type-to-dictionary-using-DynamicMethod.aspx

Upvotes: 1

Related Questions