Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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


Related questions:

  • Does the new ‘dynamic’ C# 4.0 keyword deprecate the ‘var’ keyword ?
  • What do you think of the new C# 4.0 ‘dynamic’ keyword?
like image 258
Vokinneberg Avatar asked Dec 22 '22 13:12

Vokinneberg


2 Answers

Anders Hejlsberg did a nice wee PDC session called "The Future of C#". there's a pretty good demo of the use of the dynamic keyword:

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

like image 103
Kev Avatar answered Jan 11 '23 06:01

Kev


Once you've a dynamic object, the compiler is least bothered about any method calls you might make on the dynamic object. The calls will be resolved only at the runtime. In this case, the method Read() is dispatched dynamically during run time.

What is more beautiful is, C# now gives you the flexibility to specify how the dynamic calls should be dispatched. You can implement the IDynamicObject, to write these binders yourself. For example, see how I'm creating a dynamic reader class, which allows you to call your own methods on an instance of that.

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;
        }
    }

Now, the dynamic keyword can be used to create dynamic objects, much like

dynamic reader=new DynamicReader();
dynamic data=reader.Read();
like image 38
amazedsaint Avatar answered Jan 11 '23 06:01

amazedsaint