Compartir a través de


DynamicObject.TrySetMember Method

Microsoft Silverlight will reach end of support after October 2021. Learn more.

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

Namespace:  System.Dynamic
Assembly:  System.Core (in System.Core.dll)

Syntax

'Declaration
Public Overridable Function TrySetMember ( _
    binder As SetMemberBinder, _
    value As Object _
) As Boolean
public virtual bool TrySetMember(
    SetMemberBinder binder,
    Object value
)

Parameters

  • binder
    Type: System.Dynamic.SetMemberBinder
    Provides information about the object that called the dynamic operation. The binder.Name property provides the name of the member to which the value is being assigned. For example, for the statement sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the DynamicObject class, binder.Name returns "SampleProperty". The binder.IgnoreCase property specifies whether the member name is case-sensitive.
  • value
    Type: System.Object
    The value to set to the member. For example, for sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class derived from the DynamicObject class, the value is "Test".

Return Value

Type: System.Boolean
true if the operation is successful; otherwise, false. If this method returns false, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)

Remarks

Classes derived from the DynamicObject class can override this method to specify how operations that set a value to a member should be performed for a dynamic object. When the method is not overridden, the run-time binder of the language determines the behavior. (In most cases, a language-specific run-time exception is thrown.)

This method is called when you have statements like sampleObject.SampleProperty = "Test", where sampleObject is an instance of the class that is derived from the DynamicObject class.

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.

Examples

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, this syntax must 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
    Inherits DynamicObject

    ' The inner dictionary.
    Dim dictionary As New Dictionary(Of String, Object)

    ' This property returns the number of elements
    ' in the inner dictionary.
    ReadOnly Property Count As Integer
        Get
            Return dictionary.Count
        End Get
    End Property


    ' If you try to get a value of a property that is
    ' not defined in the class, this method is called.

    Public Overrides Function TryGetMember(
        ByVal binder As System.Dynamic.GetMemberBinder,
        ByRef result As Object) As Boolean

        ' Converting the property name to lowercase
        ' so that property names become case-insensitive.
        Dim name As String = 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, result)
    End Function

    Public Overrides Function TrySetMember(
        ByVal binder As System.Dynamic.SetMemberBinder,
        ByVal value As Object) As Boolean

        ' 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
    End Function
End Class

Sub Demo(outputBlock As System.Windows.Controls.TextBlock)
    ' Creating a dynamic dictionary.
    Dim person As Object = 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 now case-insensitive,
    ' although they are case-sensitive in C#.
    outputBlock.Text &= person.firstname & " " & person.lastname & vbCrLf

    ' Getting the value of the Count property.
    ' The TryGetMember is not called, 
    ' because the property is defined in the class.
    outputBlock.Text &= "Number of dynamic properties:" & person.Count & vbCrLf

    ' The following statement throws an exception at run time.
    ' There is no "address" property,
    ' so the TryGetMember method returns false and this causes
    ' a MissingMemberException.
    ' outputBlock.Text &= person.address & vbCrLf
End Sub
' This examples has the following output:
' Ellen Adams
' Number of dynamic properties: 2
// 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 Example
{
   private static System.Windows.Controls.TextBlock outputBlock;

   public static void Demo(System.Windows.Controls.TextBlock outputBlock)
   {

      Example.outputBlock = outputBlock;
      // 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.
      outputBlock.Text += person.firstname + " " + person.lastname + "\n";

      // Getting the value of the Count property.
      // The TryGetMember is not called, 
      // because the property is defined in the class.
      outputBlock.Text +=
          "Number of dynamic properties:" + person.Count + "\n";

      // 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.
      // outputBlock.Text += person.address + "\n";
   }
}

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

Version Information

Silverlight

Supported in: 5, 4

Platforms

For a list of the operating systems and browsers that are supported by Silverlight, see Supported Operating Systems and Browsers.