Click here to Skip to main content
13,043,092 members (51,574 online)
Click here to Skip to main content
Add your own
alternative version


12 bookmarked
Posted 5 Jun 2012

dynamic type in C#.4.0 Where and how to use? How does it differ from var and object?

, 11 Jun 2012
Rate this:
Please Sign up or sign in to vote.
Where and how to use the dynamic type in C#.

Recently I was working on an API project where I had to return JSON data to the client for different kinds of Requests like Customers, Orders, Products etc. Since I was working on ASP.NET MVC, I could make use of the Json method to convert my entities ( Customer / Product etc…) to JSON format in one line of code. No matter how my entity looks like, how complex it is, the Json method will serialize that to JSON format.

I want to return a generic response to my API call which tells me whether the call is a success or failure, and if failure the reason for the failure (e.g.: Invalid input / Not authorized to make this call etc..). So one way to this is doing like this. Create a class for returning the customer data (e.g.: list of customers) with properties for the status, error message, and finally the response data (the list of customers).

Now I can return the list of customers by filling the CustomersData property with a list of customer objects.

This will work, I will get a nice JSON response which represent my entity. Great ! But wait. Look at it again. Aren’t we doing it wrong? Yes we are. We have more entities left. In this approach, We need to create a separate class for each return one for CustomersAPIResponse, one for ProductsAPIResponse, one for OrdersAPIRespons and what not? So many classes! It’s messy and we don’t really want to do with the code which we will maintain.

So what’s next ?

Here comes the dynamic type. we can use dynamic type in places where we can not tell the compiler in advance that this is going to be my type. Ex : In the above method, We told the Compiler that the CustomersData property is of type IEnumerable<Customer> . Compiler accepted that and If we are setting the value of this property as same type, the program will compile also. But if we use the dynamic type instead of the static IEnumerable<Customer>, Compiler is going to ignore that. you can set any type in that. When the program get executed , That property value will be replaced with what we are setting.

So Let’s replace our code a little bit. We will write a generic class which can be used for returning all kind of requests

You might have noticed that the type of Data Property here is dynamic. That means , It can take anything and the compiler wont care about it.

So now we can use this for all our methods.

GetMockProductData returns a list of Products and GetMockCustomerData returns a list of Customers. Our Data Property is ok to accept any type now. There is no problem.

Methods/Properties of a dynamic type will be evaluated at runtime only. Not at compile time. The compiler will assume that the object in a variable supports any operations.

Doesn’t it looks like var ?

var and dynamic are different. var is still strongly typed. So the moment you initialize the var type, It becomes that type. That means, if you write something like this

iamStrongType becomes a string type. So it is strongly typed. You can not assign a different type to this variable now like.

Another thing is, you can not define var as a property type.

So where to use var?

I think the most I use var is as a shorthand for creating new objects. Instead of writing this:

I can simply write this.

That is much cleaner.

Another scenario where you use var is to create a type on the fly. You want to return something, but you don’t want to write a class for that. So you can use var there like this.

Object vs. Dynamic 

Object is the base class. So why not use that instead of dynamic?

Yes, you can use that. But you need to do an explicit type casting every time you want to get the value back and forth.

I hope this gives you some idea about dynamic type in C#4.0. You can download the sample source code which I used in the post here. Don’t forget to leave me a comment, if this post helps you.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Software Developer (Senior)
United States United States
Shyju is a curious developer who loves to build highly scalabale and robust software on top of Microsoft development stack. He is a strong believer in test driven development and occasionally writes Tips & Tricks on ASP.NET MVC, Entity Framework, jQuery in his technical blog

Twitter : kshyju
Blog : TechiesWeb

You may also be interested in...

Comments and Discussions

BugIt seems the image links are dead now. Please update them. Pin
SaiKiran.Mandhala1-Sep-15 7:25
memberSaiKiran.Mandhala1-Sep-15 7:25 
Questioncomment Pin
Member 1055958911-Feb-14 1:19
memberMember 1055958911-Feb-14 1:19 
Questionvery well explained Pin
chaitanaya singh14-Nov-13 1:07
memberchaitanaya singh14-Nov-13 1:07 
GeneralMy vote of 5 Pin
Ameyakhedekar7-Nov-13 19:23
memberAmeyakhedekar7-Nov-13 19:23 
Questionvery helpful Pin
sunil kumar nerella6-Nov-13 1:57
membersunil kumar nerella6-Nov-13 1:57 
Questiondynamic type Pin
chidi.udeogu7-Oct-13 23:09
memberchidi.udeogu7-Oct-13 23:09 
GeneralMy vote of 5 Pin
Elio R. Batista Gonzalez5-Apr-13 10:11
memberElio R. Batista Gonzalez5-Apr-13 10:11 
GeneralMy vote of 5 Pin
ya3mro17-Mar-13 22:13
memberya3mro17-Mar-13 22:13 
GeneralMy vote 5 Pin
Kiran Sonawane21-Jun-12 1:58
memberKiran Sonawane21-Jun-12 1:58 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170713.1 | Last Updated 11 Jun 2012
Article Copyright 2012 by kshyju
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid