Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to concat C# anonymous types?

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?

like image 882
Matthew T. Avatar asked Apr 28 '10 04:04

Matthew T.


2 Answers

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.

like image 77
Yauheni Sivukha Avatar answered Sep 21 '22 11:09

Yauheni Sivukha


No - They are different types and the + operator on both those types is undefined.

As a side note: I don't think you mean concatenate. In C#, concatenate is something you do to two or more IEnumerations that puts them "end to end". For instance, the Linq method Concat() or String.Concat() (strings are "collections" of char). What you describe in your question is more like a join or multiple-inheritance between two unrelated types. I can't think of anything similar to that in C#, besides using autonomous types as in the alternative below:

var hello = new { Hello = "Hello" };
var world = new { World = "World" };
var helloWorld = new { hello, world };
Console.WriteLine(helloWorld.ToString());
//outputs { hello = { Hello = Hello }, world = { World = World } }
like image 31
Greg Avatar answered Sep 21 '22 11:09

Greg