Pier
Pier

Reputation: 10837

Is it possible to create an object without a class in C#?

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#?

Upvotes: 51

Views: 53767

Answers (3)

L.B
L.B

Reputation: 116168

Read about ExpandoObject

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

Console.WriteLine(myObject.myParameter);

Upvotes: 5

Prabhu Murthy
Prabhu Murthy

Reputation: 9261

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

Upvotes: 32

Rohit Vats
Rohit Vats

Reputation: 81253

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.

Upvotes: 96

Related Questions