Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a dynamic type from a string in C#

My question is very, very simple about C#:

We can create a dynamic type with the syntax:

dynamic dObj = new { P1 = "a", P2 = 1, p3 = DateTime.Now };

For the same result, is there any way to create that object from a string variable? like:

string sObj = @"new { P1 = "a", P2 = 1, p3 = DateTime.Now }";
dynamic dObj = [something].fromstring(sObj);

The idea is to get a object from a object built from a string, or I need a serializer to that?

like image 433
Flavio CF Oliveira Avatar asked May 02 '26 23:05

Flavio CF Oliveira


1 Answers

That requires a compiler. The ExpandoObject class pretty much does what you want:

    dynamic bag = new ExpandoObject();
    bag.P1 = "a";
    bag.P2 = 1;
    bag.p3 = DateTime.Now;

Which also solves a problem with your original code, the members of an anonymous type only have internal accessibility. In other words, your dObj object is only usable in code that lives in the same assembly.

like image 134
Hans Passant Avatar answered May 05 '26 13:05

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!