C # Practical use of a dynamic keyword

Possible duplicate:
How will you use dynamic type C # 4?

What will be the actual practical applications of the dynamic keyword?

dynamic a = 1; a.Crash(); 

I know the case when it is read in XML chains, but besides this, what is it useful for?

+4
source share
6 answers

Here is a good article:

As a developer, you use a dynamic keyword with variables expected to contain objects of an undefined type, such as objects returned from the COM or DOM API; obtained from a dynamic language (for example, IronRuby); out of reflection; from built objects dynamically in C # 4.0 using a new feature extension.

Using a dynamic keyword in C # 4.0

+4
source

This is especially useful in COM interaction scenarios where you usually have to write a lot of plumbing code.

+2
source

The most practical use I've found relates to COM interaction scenarios. Many legacy COM components end up generating signatures that are unsuitable for use with managed code without a lot of castings due to the fact that many elements become marshaled as an object . This leads to the following code.

 IUser GetAUser() { ... } IUser user = GetAUser(); IAddress address = (IAddress)user.GetAddress(); int zipCode = (int)address.GetZipCode(); 

This gets worse with deeply nested hierarchies. Although this code is type safe in the sense that it does not violate any CLR rules, it is unsafe in the sense that the developer depends on the details of the type implementation to do the job. It is truly safer than the dynamic equivalent.

 dynamic GetAUser() { ... } int zipCode = (int)GetAUser().GetAddress().GetZipCode(); 
+1
source

DLR (Dynamic Language Runtime) basically allows everyone to talk to everyone. This includes not only Python and Ruby, but also Silverlight, Office / COM, and others.

0
source

As Chris said, this is very useful in COM interaction scenarios.

It is also very useful on . You may have views with a dynamic model. You also have a ViewBag object that can contain anything.

And one more use is a json object if you implement the DynamicObject class . This is very useful when using the API.

0
source

Using a dynamic keyword with POCOs can be extremely useful if you have multiple method overloads and get the argument as an object. Convert the argument to dynamic, and it will allow the correct overload depending on the type of runtime. Without dynamic ends, we get a series of if / elseif, yuck statements.

Using a dynamic keyword with subclasses of DynamicObjects allows you to get rid of the boiler plate, it is easier to write free api and create code that is much more malleable. For example, here is a dynamic api that gets rid of a ton of template code associated with MVVM binding http://code.google.com/p/impromptu-interface/wiki/UsageMVVM

0
source

All Articles