MOCKSTACKS
EN
Questions And Answers

More Tutorials




Convert Dictionary To Anonymous Object in C#

To convert dictionary to an object we can use< code>ExpandoObject which represents an object whose members can be dynamically added and removed at run time, this class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

Remember to include all required namespaces: using System;, using System.Collections.Generic;, using System.Dynamic;.

Example

using System;
using System.Collections.Generic;
using System.Dynamic;

public class Example
{
    public class Location
    {
	public string city { get; set; }
	public string state { get; set; }
	public string country { get; set; }
    }

    public static void Main()
    {
	var dict = new Dictionary<string, object> 
			{ { "city", "Detroit" }, {"state", "Michigan"}, {"country", "USA"} };
	var eo = new ExpandoObject();
	var eoColl = (ICollection<KeyValuePair<string, object>>)eo;

	foreach (var kvp in dict)
	{
		eoColl.Add(kvp);
	}

	dynamic eoDynamic = eo;
	Console.WriteLine(eoDynamic.city);
    }
}

Output

Detroit

Conclusion

In this page (written and validated by ) you learned about Convert Dictionary To Anonymous Object in C# . What's Next? If you are interested in completing C# tutorial, we encourage you simply to start here: C# Tutorial.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.