Show me how to use the new dynamic keyword in C # 4.0

Here is the new future of C # in version 4.0, known as dynamic. Show me how I can use it in my code and how this future can help me?


Related questions:

+4
source share
4 answers

Anders Halesberg did a pretty good PDC session entitled "Future C #". there is a pretty good demonstration of using a dynamic keyword:

http://channel9.msdn.com/pdc2008/TL16/

+3
source

Once you have a dynamic object, the compiler is least worried about any method calls that you could make for the dynamic object. Calls will only be allowed at run time. In this case, the Read () method is dispatched dynamically at run time.

More beautiful, C # now gives you the flexibility to determine how dynamic calls should be sent. You can implement IDynamicObject to write these binders yourself. For example, see how I create a dynamic reading class that allows you to call your own methods on an instance of this.

public class DynamicReader : IDynamicObject { public MetaObject GetMetaObject (System.Linq.Expressions.Expression parameter) { return new DynamicReaderDispatch (parameter); } } public class DynamicReaderDispatch : MetaObject { public DynamicReaderDispatch (Expression parameter) : base(parameter, Restrictions.Empty){ } public override MetaObject Call(CallAction action, MetaObject[] args) { //You might implement logic for dynamic method calls. Action.name // will give you the method name Console.WriteLine("Logic to dispatch Method '{0}'", action.Name); return this; } } 

You can now use the dynamic keyword to create dynamic objects, like

 dynamic reader=new DynamicReader(); dynamic data=reader.Read(); 
+3
source

We use the C # keyword "dynamic" with TDD.

This code does not compile because the Add-on method is not implemented

 [TestMethod()] public void CalculatorThingAdd_2PositiveNumbers_ResultAdded() { CalculatorThing myCalculator = new CalculatorThing(); int result = 0; int expcected = 3; // --> CalculatorThing does not contain a definition for 'Addition' result = myCalculator.Addition(1, 2); Assert.AreEqual(result, expcected); } 

With the keyword "dynamic" the code compiles and the test fails! โ†’ TDD

See the answer here https://stackoverflow.com/questions/244302/what-do-you-think-of-the-new-c-4-0-dynamic-keyword/2243818#2243818

+3
source

One of the usages is the interaction between static and dynamic languages.

Suppose you want to call the JavaScript function fron silverlight:

 HtmlPage.Window.Invoke("HelloWorldFunction"); 

If the window was dynamic (and correctly implemented), you could use it as follows:

 HtmlPage.Window.HelloWorldFunction(); 
+2
source

All Articles