views:

212

answers:

3

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?

+3  A: 

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.

Yauheni Sivukha
I would venture that if you need to do all this for this kind of thing, you're using the anonymous types wrong.
Lasse V. Karlsen
I'm going to have to agree with Lasse. While it might be an interesting workaround, its not a reasonable solution. Thanks for letting me know its not possible.
Matthew T.
A: 

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 } }
Greg
Concatenation was the best word I could find to describe the merging of two anonymous types; each with its own "collections" of members.
Matthew T.
+1  A: 
var helloWorld = new { Hello = hello.Hello, World = world.World };

You can write a method that does this automatically using reflection API. That's as close to this as I see possible.

kervin