Export (0) Print
Expand All

DynamicObject Class

Provides a base class for specifying dynamic behavior at run time. This class must be inherited from; you cannot instantiate it directly.

System.Object
  System.Dynamic.DynamicObject

Namespace:  System.Dynamic
Assemblies:   System.Dynamic.Runtime (in System.Dynamic.Runtime.dll)
  System.Core (in System.Core.dll)

public class DynamicObject : IDynamicMetaObjectProvider

The DynamicObject type exposes the following members.

  NameDescription
Protected methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsDynamicObjectEnables derived types to initialize a new instance of the DynamicObject type.
Top

  NameDescription
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsEquals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsFinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetDynamicMemberNamesReturns the enumeration of all dynamic member names.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetHashCodeServes as the default hash function. (Inherited from Object.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetMetaObjectProvides a DynamicMetaObject that dispatches to the dynamic virtual methods. The object can be encapsulated inside another DynamicMetaObject to provide custom behavior for individual actions. This method supports the Dynamic Language Runtime infrastructure for language implementers and it is not intended to be used directly from your code.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsGetTypeGets the Type of the current instance. (Inherited from Object.)
Protected methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsMemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsToStringReturns a string that represents the current object. (Inherited from Object.)
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryBinaryOperationProvides implementation for binary operations. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as addition and multiplication.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryConvertProvides implementation for type conversion operations. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations that convert an object from one type to another.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryCreateInstanceProvides the implementation for operations that initialize a new instance of a dynamic object. This method is not intended for use in C# or Visual Basic.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryDeleteIndexProvides the implementation for operations that delete an object by index. This method is not intended for use in C# or Visual Basic.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryDeleteMemberProvides the implementation for operations that delete an object member. This method is not intended for use in C# or Visual Basic.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryGetIndexProvides the implementation for operations that get a value by index. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for indexing operations.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryGetMemberProvides the implementation for operations that get member values. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as getting a value for a property.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryInvokeProvides the implementation for operations that invoke an object. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as invoking an object or a delegate.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryInvokeMemberProvides the implementation for operations that invoke a member. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as calling a method.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTrySetIndexProvides the implementation for operations that set a value by index. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations that access objects by a specified index.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTrySetMemberProvides the implementation for operations that set member values. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as setting a value for a property.
Public methodSupported by Portable Class LibrarySupported in .NET for Windows Store appsTryUnaryOperationProvides implementation for unary operations. Classes derived from the DynamicObject class can override this method to specify dynamic behavior for operations such as negation, increment, or decrement.
Top

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 from 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.

In C#, to enable dynamic behavior for 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 (Visual Basic).

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 ();

You can also add your own members to classes derived from the DynamicObject class. If your class defines properties and also overrides the TrySetMember method, the dynamic language runtime (DLR) first uses the language binder to look for a static definition of a property in the class. If there is no such property, the DLR calls the TrySetMember method.

The DynamicObject class implements the 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.

NoteNote

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 specific operations and does not have static members, 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.

Assume that you want to provide alternative syntax for accessing values in a dictionary, so that instead of writing sampleDictionary["Text"] = "Sample text" (sampleDictionary("Text") = "Sample text" in Visual Basic), you can write sampleDictionary.Text = "Sample text". Also, you want this syntax to be case-insensitive, so that sampleDictionary.Text is equivalent to sampleDictionary.text.

The following code example demonstrates the DynamicDictionary class, which is derived from the DynamicObject class. The DynamicDictionary class contains an object of the Dictionary<string, object> type (Dictionary(Of String, Object) in Visual Basic) to store the key-value pairs, and overrides the TrySetMember and TryGetMember methods to support the new syntax. It also provides a Count property, which shows how many dynamic properties the dictionary contains.

// The class derived from DynamicObject. 
public class DynamicDictionary : DynamicObject
{
    // The inner dictionary.
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

    // This property returns the number of elements 
    // in the inner dictionary. 
    public int Count
    {
        get
        {
            return dictionary.Count;
        }
    }

    // If you try to get a value of a property  
    // not defined in the class, this method is called. 
    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        // Converting the property name to lowercase 
        // so that property names become case-insensitive. 
        string name = binder.Name.ToLower();

        // If the property name is found in a dictionary, 
        // set the result parameter to the property value and return true. 
        // Otherwise, return false. 
        return dictionary.TryGetValue(name, out result);
    }

    // If you try to set a value of a property that is 
    // not defined in the class, this method is called. 
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        // Converting the property name to lowercase 
        // so that property names become case-insensitive.
        dictionary[binder.Name.ToLower()] = value;

        // You can always add a value to a dictionary, 
        // so this method always returns true. 
        return true;
    }
}

class Program
{
    static void Main(string[] args)
    {
        // Creating a dynamic dictionary.
        dynamic person = new DynamicDictionary();

        // Adding new dynamic properties.  
        // The TrySetMember method is called.
        person.FirstName = "Ellen";
        person.LastName = "Adams";

        // Getting values of the dynamic properties. 
        // The TryGetMember method is called. 
        // Note that property names are case-insensitive.
        Console.WriteLine(person.firstname + " " + person.lastname);

        // Getting the value of the Count property. 
        // The TryGetMember is not called,  
        // because the property is defined in the class.
        Console.WriteLine(
            "Number of dynamic properties:" + person.Count);

        // The following statement throws an exception at run time. 
        // There is no "address" property,
        // so the TryGetMember method returns false and this causes a 
        // RuntimeBinderException. 
        // Console.WriteLine(person.address);
    }
}

// This example has the following output: 
// Ellen Adams 
// Number of dynamic properties: 2

For more examples, see Creating Wrappers with DynamicObject on the C# Frequently Asked Questions blog.

.NET Framework

Supported in: 4.6, 4.5, 4

.NET Framework Client Profile

Supported in: 4

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8

Windows Phone 8.1, Windows Phone 8, Windows 8.1, Windows Server 2012 R2, Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
Show:
© 2014 Microsoft