Blog

ExpandoObject in C# 4.0

Posted by Amit Patel Blogs | C# Language Jun 13, 2012
In this short blog I will explain about the ExpandoObject in C# 4.0, it's really dynamic.

Introduction

ExpandoObject it like a expand property in HTML. Microsoft introduces new class ExpandoObject. It's really dynamic object. It is part of DLR (dynamic language runtime).

The ExpandoObject class enables you to add and delete members of its instances at run time and also to set and get values of these members. This class supports dynamic binding, which enables you to use standard syntax like sampleObject.sampleMember instead of more complex syntax like sampleObject.GetAttribute("sampleMember").

http://msdn.microsoft.com/en-us/library/system.dynamic.expandoobject(VS.100).aspx

Purpose: To create a runtime instance of any type. You can add properties, methods, and events to instances of the ExpandoObject class.

Code

Here we are creating dynamic instance.

dynamic Employee = new ExpandoObject();
Employee.ID = 1;
Employee.Name =
"Amit";
Employee.Salary = 10000;

Nested dynamic instance


Employee.Addess = new ExpandoObject();
Employee.Addess.City =
"Pune";
Employee.Addess.Country =
"India";
Employee.Addess.PinCode = 456123;

Bind dynamic Event

Employee.Click += new EventHandler(SampleHandler);
private void SampleHandler(object sender, EventArgs e)
{
    //throw new NotImplementedException();
}

Pass parameter as dynamic.
 
public void Write(dynamic employee)
{
    //you can write your logic
}

Happy coding

post comment
     
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter