Reputation: 83
Can I dynamically create a property type and property name for an (anonymous) object if the name and type I get from a string variable?
Upvotes: 2
Views: 332
Reputation: 39956
In c# 4.0 onwards you can use dynamic keyword with DynamicObject object based on dictionary to create/extend properties at runtime very much like JavaScript.
Upvotes: 1
Reputation: 545
If you're talking about anonymous types (such as var x = new { Property1 = data1, ...}
) then I don't think that you can.
What you might be able to do is create another new anonymous type from the one you already have. Where you want to create Y
from X
, you could create Y
by var Y = new { YProp1 = X.Prop1, YProp2 = X.Prop2, etc}
Upvotes: 1
Reputation: 19635
C# .NET is a statically typed language, meaning that all classes must be defined at compile time. So, the knee-jerk answer to your question is no.
However, like most languages, there are workarounds that you can use. For instance, you can create a class that has a Dictionary<string,object>
type property that will take your property names as keys and your property values as values.
Of course, the downside to this is that you will need to write extra code to verify that the data in the dictionary is valid... so it may not be worth it.
Upvotes: 0
Reputation: 241769
For anonymous classes, no. These are defined at compile-time by the compiler.
Upvotes: 0