The DynamicObject class enables you to define which operations can be performed on dynamic objects and how to perform those operations. For example, you can define what happens when you try to get or set an object property, call a method, or perform standard mathematical operations such as addition and multiplication.
This class can be useful if you want to create a more convenient protocol for a library. For example, if users of your library have to use syntax like Scriptobj.SetProperty("Count", 1), you can provide the ability to use much simpler syntax, like scriptobj.Count = 1.
You cannot directly create an instance of the DynamicObject class. To implement the dynamic behavior, you may want to inherit the DynamicObject class and override necessary methods. For example, if you need only operations for setting and getting properties, you can override just the TrySetMember and TryGetMember methods.
You can also add your own members to classes derived from the DynamicObject class. For example, if you override the TrySetMember method, the dynamic dispatch system first tries to determine whether the specified property exists in the class. If it does not find the property, it uses the TrySetMember implementation.
In C#, to create instances of classes derived from the DynamicObject class, you must use the dynamic keyword. For more information, see Using Type dynamic (C# Programming Guide).
In Visual Basic, dynamic operations are supported by late binding. For more information, see Early and Late Binding.
The following code example demonstrates how to create an instance of a class that is derived from the DynamicObject class.
public class SampleDynamicObject : DynamicObject {}
//...
dynamic sampleObject = new SampleDynamicObject ();
Public Class SampleDynamicObject
Inherits DynamicObject
'...
Dim sampleObject As Object = New SampleDynamicObject()
The DynamicObject class implements the standard dynamic language runtime (DLR) interface IDynamicMetaObjectProvider, which enables you to share instances of the DynamicObject class between languages that support the DLR interoperability model. For example, you can create an instance of the DynamicObject class in C# and then pass it to an IronPython function. For more information, see Dynamic Language Runtime Overview and documentation on the CodePlex Web site.
Note |
|---|
If you have a simple scenario in which you need an object that can only add and remove members at run time but that does not need to define operation specifics, use the ExpandoObject class. If you have a more advanced scenario in which you need to define how dynamic objects participate in the interoperability protocol, or you need to manage DLR fast dynamic dispatch caching, create your own implementation of the IDynamicMetaObjectProvider interface. |