Is there a way to concat C# anonymous types?

Matthew T. picture Matthew T. · Apr 28, 2010 · Viewed 7k times · Source

For example

var hello = new { Hello = "Hello" };
var world = new { World = "World" };
var helloWorld = hello + world;
Console.WriteLine(helloWorld.ToString());
//outputs {Hello = Hello, World = World}

Is there any way to make this work?

Answer

Yauheni Sivukha picture Yauheni Sivukha · Apr 28, 2010

No. hello and world objects are objects of different classes.

The only way to merge these classes is to use dynamic type generation (Emit). Here is example of such concatenation: http://www.developmentalmadness.com/archive/2008/02/12/extend-anonymous-types-using.aspx

Quote from mentioned article:

The process works like this: First use System.ComponentModel.GetProperties to get a PropertyDescriptorCollection from the anonymous type. Fire up Reflection.Emit to create a new dynamic assembly and use TypeBuilder to create a new type which is a composite of all the properties involved. Then cache the new type for reuse so you don't have to take the hit of building the new type every time you need it.