Click here to Skip to main content
Click here to Skip to main content

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.

License

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

Share

About the Author

kshyju
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 www.techiesweb.net.
 
Twitter : kshyju
Blog : TechiesWeb
Follow on   Twitter

Comments and Discussions

 
Questioncomment PinmemberMember 1055958911-Feb-14 1:19 
Questionvery well explained Pinmemberchaitanaya singh14-Nov-13 1:07 
GeneralMy vote of 5 PinmemberAmeyakhedekar7-Nov-13 19:23 
Questionvery helpful Pinmembersunil kumar nerella6-Nov-13 1:57 
Questiondynamic type Pinmemberchidi.udeogu7-Oct-13 23:09 
GeneralMy vote of 5 PinmemberElio R. Batista Gonzalez5-Apr-13 10:11 
GeneralMy vote of 5 Pinmemberya3mro17-Mar-13 22:13 
GeneralMy vote 5 PinmemberKiran Sonawane21-Jun-12 1:58 

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

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

| Advertise | Privacy | Mobile
Web02 | 2.8.140827.1 | Last Updated 11 Jun 2012
Article Copyright 2012 by kshyju
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid