What is Dynamic and ExpandoObject in c#?

Reading Time: 3 minutes

Introduction

In this article, I wanna explain what is Dynamic and ExpandoObject in C# and give you some examples.

Type “dynamic” was introduced in c# 4. In general and in most cases it acts as a type “object“.

An object with type “dynamic” can support any operation and you can call any function name or property name, and in compile time if what you called doesn’t exist, then an error will be raised.

This type of objects can get its data from anywhere like Web Apis (JSON responses) or HTML DOMs and so on.

In other words: The dynamic keyword is used to tell the compiler that a variable’s type and its methods and properties can change or that it is not known until runtime.

Don’t worry if the concept is unclear. I will show you some examples and you will not make you leave without a clear explanation.

 

sample example:

dynamic car = GetCar();
cust.Color= "green"; // works as expected
cust.Move(); // works as expected
cust.MissingMethod(); // No method found!

Difference between var and dynamic.

Dynamically typed – This means the type of variable declared is decided by the compiler at runtime time. Errors are caught at runtimeIntellisense is not available since the type and its related methods and properties can’t be known by the compiler.

var

dynamic

C# 3.0 C# 4.0
You have to initialize when declaring.

var number = 0;

Looking at the value assigned to the variable,number the compiler will treat the variable number as an integer.

No need to initialize when declared.

dynamic number;

number="Sample string" //Works fine and compiles

number=2; //Works fine and compiles

Visual Studio shows intellisense since the type of variable assigned is known to the compiler. No intellisense, Errors are caught at compile time.

 

ExpandoObject

The ExpandoObject class enables you to add and delete members of its instances at runtime and also to set and get values of these members.

This class supports dynamic binding, which enables you to use standard syntax like

obj1.property1
obj1.method1
//instead of more complex syntax like:
obj1.GetAttribute("property1").

Example:

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

Detailed example:

In My Course “Facebook API: Automate facebook tasks using C#“, when I was working with automating tasks on my pages like posting images, videos, and links in and schedule them in bulk, I had to send a POST request to the API and add some properties in that call.

let’s take a look at how I used dynamic and expando to accomplish that:

Posting an image to facebook page code:

 

// declare facebook client 
FacebookClient fbclient = new FacebookClient(pageToken); 

//get date in unix format
string dts = DateTimeConvertor.ToUnixTime(schedDate).ToString(); 

//declate a dynamic object type since I wanna use the properties at run time 
dynamic parameters = new ExpandoObject();

//set the parameters, parameters name are detected if correct by the
//facebook API (server Side) which means if I misspelled one of them
//the compiler at compile time //will not about it.
 

//At run time if the facebook api raises an error then at runtime
//my application will through an error.
parameters.scheduled_publish_time = dts;
parameters.published = false;

if (description != null)
{
parameters.message = description;

}

parameters.source = new FacebookMediaObject
{
ContentType = "image/" + Path.GetExtension(imgPath),
FileName = imgPath

}.SetValue(File.ReadAllBytes(imgPath));

//Here the facebook API will recieve my call 
//and check if the parameters are correct.
fbclient.Post(pageid + "/photos", parameters);

 

I Hope you got the point.

Please if you have any questions? or if you need any more details, comment below or submit your question on the Questions page.

 

Leave a Comment

Your email address will not be published. Required fields are marked *