Using the C# object initializer syntax I can instantiate an anonymous object like this:
object empData = new { name = "bob", age = 30, salary = 100000 };
But what if I have the initializer stored in a string, e.g.:
string init = "{ name = \"bob\", age = 30, salary = 100000 }";
Whats the best way of converting this string into an instance of the 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 .
You create an anonymous type using the new operator with an object initializer syntax. The implicitly typed variable- var is used to hold the reference of anonymous types.
Anonymous object in Java means creating an object without any reference variable. Generally, when creating an object in Java, you need to assign a name to the object. But the anonymous object in Java allows you to create an object without any name assigned to that object.
In C#, you are allowed to create an anonymous type object with a new keyword without its class definition and var is used to hold the reference of the anonymous types. As shown in the below example, anony_object is an anonymous type object which contains three properties that are s_id, s_name, language.
Anonymous classes are C# syntactic sugar (see Remarks section here). csc.exe creates a class with private fields and a read/write property with the type inferred from context. All uses of the object are, again, inferred.
What this means is you cannot create an anonymous class at run time because the CLR sees them no differently than any other class (again, because it is C# syntactic sugar).
So instead:
Dictionary<string,object>
System.Reflection.Emit
to create the type at run-time, but I see no real benefit to this over just a Dictionary<string,object>
I also have concerns of what you're doing because this as a string very likely means to me that you are accepting user input of some kind. Be wary of the security issues in whatever you do.
It's not possible using anonymous types, however you can do it with Reflection Emit using the TypeBuilder class, specifically TypeBuilder.Create(..).
http://msdn.microsoft.com/en-us/library/system.reflection.emit.typebuilder.createtype.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With