0

I'm trying to create an anonymous type based on string parameters for example,

var propertyName = "Firstname";
var properyValue = "Fred";

I would like to be able to get;

var myObj = new { FirstName = "Fred" };

But also having the opportunity of using the same function and having;

var propertyName = "Surname";
var properyValue = "Smith";
var myObj = new { Surname = "Smith" };

Is this actually possible?

3
  • Are you looking for ExpandoObject? Commented Apr 11, 2017 at 13:05
  • 3
    What? Unclear what you want... Use a Dictionary<string, string> and live happy. Commented Apr 11, 2017 at 13:05
  • Maybe look at ExpandoObject, but why do you want to do that? It might be possible that you've got a XY Problem Commented Apr 11, 2017 at 13:05

1 Answer 1

1

Anonymous types are defined at compile-time. They're normal C# types, just without a name [1]. As such, you cannot modify their structure based on runtime information.

It doesn't seem like you want anonymous types at all, really. ExpandoObject sounds more like what you want. Anonymous types shouldn't leak from their scope - and if you follow that, you don't ever need a way to construct them dynamically like you're trying to do.

Additionally, be careful when you expose an anonymous type. There's a reason why they aren't allowed to be used as method arguments and return types - that isn't what they're designed for. It seems you're circumventing this limitation by using dynamic, but that has many problems; it can stop working with any release of .NET (including hotfixes), and with current .NET, it will cause you accessibility errors if you leak the anonymous typed to where it shouldn't be (e.g. an internal anonymous type used in a different assembly).

[1] Of course, they actually do have a name, since the CLR requires types to have a name. But the name is autogenerated and somewhat hidden, and not something you should ever take into account.

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.