1

In JavaScript, I can create a new object (called clean). Then if I want to set an attribute of that object I just set objectName.attributeName = whatever. Is it possible to do something similar in C#, WITHOUT defining a class?


var clean = new Object();
clean.isClean = true;
James Madison
  • 337
  • 1
  • 4
  • 17

1 Answers1

3

Since .NET 4.0 yes, you can using ExpandoObject:

dynamic expando = new ExpandoObject();
expando.text = "hello world";

Anyway, if you're just looking to create objects on-the-fly, you should use an anonymous type declaration:

var obj = new { text = "hello world" };

Actually, expando objects have an added value: you can also add methods using delegates. For example:

dynamic expando = new ExpandoObject();
expando.DoIt = new Action
(
    () => 
    {
        // Code here
    }
);

expando.DoIt();
Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206