49

In many languages you can create an object without creating a data type, and add properties to that object.

For example in JS or AS:

 var myObject = {};
 myObject.myParameter = "hello world";

Or you can create structures in C and C++.

Is it possible to do that in C#?

0

3 Answers 3

94

Anonymous Types is what you looking for. Eg -

var v = new { Amount = 108, Message = "Hello" };

Above code will create a new object with properties Amount and Message.

4
  • Is this approach better o worse than the expandoobject from the other answers? Why?
    – Pier
    Commented Oct 21, 2012 at 18:15
  • 4
    @Pier, this approach is slightly more performant than dynamic as it's actually defining a type at compile time. There is the preferred approach if you need to organize some data together for local use (such as when performing a LINQ operation that combines data from multiple sources.) Dynamic is more flexible (you can keep adding fields as you need them), but heavier.
    – Dan Bryant
    Commented Oct 21, 2012 at 18:20
  • 5
    @Pier They are completely different things. Anonymous classes are determined at compile time. So you can not add/change a property at runtime.
    – L.B
    Commented Oct 21, 2012 at 18:22
  • Thanks for you clarification. ExpandoObject is closer to what I need then, so I will vote any of the two other answers right.
    – Pier
    Commented Oct 21, 2012 at 18:24
32

Yes there is ExpandoObject under System.Dynamic namespace.You could add properties on the fly like you do in other dynamic languages

dynamic dynObject = new ExpandoObject();
dynObject.someProperty= "Value";

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject.aspx

5

Read about ExpandoObject

dynamic myObject = new ExpandoObject();
myObject.myParameter = "hello world";

Console.WriteLine(myObject.myParameter);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.