3

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?

7
  • 2
    That's actually creating a statically typed compile time safe object of anonymous type, that happens to also be dynamic at compile time. That is not the same thing by any strech of the imagination. Commented Aug 9, 2012 at 15:52
  • OK, but is it possible to do? without a serializer? Commented Aug 9, 2012 at 15:58
  • 1
    What are you actually trying to accomplish that you came to this as an answer? There probably a better way... Commented Aug 9, 2012 at 15:59
  • Well as the data in the string is, in effect, "serialized" by virtue of it being in a persistable form, the answer to the question is "no"; you need some form of deserializer. It doesn't have to be built in, though; you could roll your own to parse this anonymous declaration. Commented Aug 9, 2012 at 16:00
  • @KeithS An inherited expando would probably do nicely. Commented Aug 9, 2012 at 16:01

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.