Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create anonymous object by Reflection in C#

Is there any way to create C# 3.0 anonymous object via Reflection at runtime in .NET 3.5? I'd like to support them in my serialization scheme, so I need a way to manipulate them programmatically.

edited later to clarify the use case

An extra constraint is that I will be running all of it inside a Silverlight app, so extra runtimes are not an option, and not sure how generating code on the fly will work.

like image 651
Michael Pliskin Avatar asked Sep 22 '08 09:09

Michael Pliskin


People also ask

How do I make an anonymous object?

You create anonymous types by using the new operator together with an object initializer. For more information about object initializers, see Object and Collection Initializers. The following example shows an anonymous type that is initialized with two properties named Amount and Message .

Can an object be anonymous?

An anonymous object is basically a value that has been created but has no name. Since they have no name, there's no other way to refer to them beyond the point where they are created. Consequently, they have “expression scope,” meaning they are created, evaluated, and destroyed everything within a single expression.

What is an anonymous type in C#?

Anonymous types in C# are the types which do not have a name or you can say the creation of new types without defining them. It is introduced in C# 3.0. It is a temporary data type which is inferred based on the data that you insert in an object initializer.

What is the difference between an anonymous type and a regular data type?

From the perspective of the common language runtime, an anonymous type is no different from any other reference type, except that it cannot be cast to any type except for object.


2 Answers

Here is another way, seems more direct.

object anon = Activator.CreateInstance(existingObject.GetType());
like image 112
Guvante Avatar answered Oct 05 '22 02:10

Guvante


Yes, there is. From memory:

public static T create<T>(T t)
{
    return Activator.CreateInstance<T>();
}

object anon = create(existingAnonymousType);
like image 24
TraumaPony Avatar answered Oct 05 '22 01:10

TraumaPony