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?
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?
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.
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 IEnumeration
s 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 } }
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.