.NET Framework Class Library
DynamicObject..::.TryUnaryOperation Method

[This documentation is for preview only, and is subject to change in later releases. Blank topics are included as placeholders.]

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

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

Visual Basic (Declaration)
Public Overridable Function TryUnaryOperation ( _
    binder As UnaryOperationBinder, _
    <OutAttribute> ByRef result As Object _
) As Boolean
Visual Basic (Usage)
Dim instance As DynamicObject
Dim binder As UnaryOperationBinder
Dim result As Object
Dim returnValue As Boolean

returnValue = instance.TryUnaryOperation(binder, _
    result)
C#
public virtual bool TryUnaryOperation(
    UnaryOperationBinder binder,
    out Object result
)
Visual C++
public:
virtual bool TryUnaryOperation(
    UnaryOperationBinder^ binder, 
    [OutAttribute] Object^% result
)
F#
abstract TryUnaryOperation : 
        binder:UnaryOperationBinder * 
        result:Object byref -> bool 
override TryUnaryOperation : 
        binder:UnaryOperationBinder * 
        result:Object byref -> bool 

Parameters

binder
Type: System.Dynamic..::.UnaryOperationBinder
Provides information about the type of the unary operation. The binder.Operation property returns the object of the ExpressionType type. For example, for the negativeNumber = -number statement, where number is derived from the DynamicObject class, binder.Operations returns "Negate".
result
Type: System..::.Object%
The result of the unary operation.

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 run-time exception is thrown.)
Remarks

Classes derived from the DynamicObject class can override this method to specify how unary operations 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 run-time exception is thrown.)

This method is called when you have unary operations such as negation, increment, or decrement. For example, if the TryUnaryOperation method is overridden, this method is automatically invoked for statements like negativeNumber = -number, where number is derived from the DynamicObject class.

You can get information about the type of the unary operation by using the Operation property of the binder parameter. The binder.Operation property can have one of the following values from the ExpressionType enumeration.

NoteNote

To implement OrElse (a || b) and AndAlso (a && b) operations for dynamic objects in C#, you may want to implement both the TryUnaryOperation method and the TryBinaryOperation method.

The OrElse operation consists of the unary IsTrue operation and the binary Or operation. The Or operation is performed only if the result of the IsTrue operation is false.

The AndAlso operation consists of the unary IsFalse operation and the binary And operation. The And operation is performed only if the result of the IsFalse operation is false.

Value

Description

C#

Visual Basic

Decrement

A unary decrement operation.

a--

Not supported.

Increment

A unary increment operation.

a++

Not supported.

Negate

An arithmetic negation.

-a

-a

Not

A logical negation.

!a

Not a

OnesComplement

A ones complement.

~a

Not supported.

IsFalse

A false condition value.

a && b

Not supported.

IsTrue

A true condition value.

a || b

Not supported.

UnaryPlus

A unary plus.

+a

+a

Examples

Assume that you need a data structure to store textual and numeric representations of numbers, and you want to define a mathematical negation operation for such data.

The following code example demonstrates the DynamicNumber class, which is derived from the DynamicObject class. DynamicNumber overrides the TryUnaryOperation method to enable the mathematical negation operation. Is also overrides the TrySetMember and TryGetMember methods to enable access to the elements.

In this example, only the mathematical negation operation is supported. If you try to write a statement like negativeNumber = +number, a run-time exception occurs.

C#
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Linq.Expressions;

// The class derived from DynamicObject.
public class DynamicNumber : DynamicObject
{
    // The inner dictionary to store field names and values.
    Dictionary<string, object> dictionary
        = new Dictionary<string, object>();

    // Get the property value.
    public override bool TryGetMember(
        GetMemberBinder binder, out object result)
    {
        return dictionary.TryGetValue(binder.Name, out result);
    }

    // Set the property value.
    public override bool TrySetMember(
        SetMemberBinder binder, object value)
    {
        dictionary[binder.Name] = value;
        return true;
    }

    // Perform the unary operation. 
    public override bool TryUnaryOperation(
        UnaryOperationBinder binder, out object result)
    {
        // The Textual property contains 
        // the name of the unary operation in addition 
        // to the textual representaion of the number.
        string resultTextual =
             binder.Operation + " " +
             dictionary["Textual"].ToString();
        int resultNumeric;

        // Determining what type of operation is being performed.
        switch (binder.Operation)
        {
            case ExpressionType.Negate:
                resultNumeric =
                     -(int)dictionary["Numeric"];
                break;
            default:
                // In case of any other unary operation,
                // print out the type of operation and return false,
                // which means that the language should determine 
                // what to do.
                // (Usually the language just throws an exception.)            
                Console.WriteLine(
                    binder.Operation +
                    ": This unary operation is not implemented");
                result = null;
                return false;
        }

        dynamic finalResult = new DynamicNumber();
        finalResult.Textual = resultTextual;
        finalResult.Numeric = resultNumeric;
        result = finalResult;
        return true;
    }
}
   
class Program
{
    static void Main(string[] args)
    {
        // Creating the first dynamic number.
        dynamic number = new DynamicNumber();

        // Creating properties and setting their values
        // for the dynamic number.
        // The TrySetMember method is called.
        number.Textual = "One";
        number.Numeric = 1;

        // Printing out properties. The TryGetMember method is called.
        Console.WriteLine(
            number.Textual + " " + number.Numeric);

        dynamic negativeNumber = new DynamicNumber();

        // Performing a mathematical negation.
        // TryUnaryOperation is called.
        negativeNumber = -number;

        Console.WriteLine(
            negativeNumber.Textual + " " + negativeNumber.Numeric);
       
        // The following statement produces a run-time exception
        // because the unary plus operation is not implemented.
        // negativeNumber = +number;
    }
}

// This code example produces the following output:

// One 1
// Negate One -1
Visual Basic
Imports System.Linq.Expressions
Imports System.Dynamic

' The class derived from DynamicObject.
Public Class DynamicNumber
    Inherits DynamicObject

    ' The inner dictionary to store field names and values.
    Dim dictionary As New Dictionary(Of String, Object)

    ' Get the property value.
    Public Overrides Function TryGetMember(
        ByVal binder As System.Dynamic.GetMemberBinder, 
        ByRef result As Object) As Boolean

        Return dictionary.TryGetValue(binder.Name, result)

    End Function

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

        dictionary(binder.Name) = value
        Return True

    End Function

    ' Perform the unary operation. 
    Public Overrides Function TryUnaryOperation(
        ByVal binder As System.Dynamic.UnaryOperationBinder,
        ByRef result As Object) As Boolean

        ' The Textual property contains the name of the unary operation
        ' in addition to the textual representaion of the number.
        Dim resultTextual As String =
        binder.Operation.ToString() & " " &
        dictionary("Textual")
        Dim resultNumeric As Integer

        ' Determining what type of operation is being performed.
        Select Case binder.Operation
            Case ExpressionType.Negate
                resultNumeric = -CInt(dictionary("Numeric"))
            Case Else
                ' In case of any other unary operation,
                ' print out the type of operation and return false,
                ' which means that the language should determine 
                ' what to do.
                ' (Usually the language just throws an exception.)            
                Console.WriteLine(
                    binder.Operation.ToString() &
                    ": This unary operation is not implemented")
                result = Nothing
                Return False
        End Select

        Dim finalResult As Object = New DynamicNumber()
        finalResult.Textual = resultTextual
        finalResult.Numeric = resultNumeric
        result = finalResult
        Return True
    End Function    
End Class


Module Module1
    Sub Main()
        ' Creating the first dynamic number.
        Dim number As Object = New DynamicNumber()

        ' Creating properties and setting their values
        ' for the dynamic number.
        ' The TrySetMember method is called.
        number.Textual = "One"
        number.Numeric = 1

        ' Printing out properties. The TryGetMember method is called.
        Console.WriteLine(
            number.Textual & " " & number.Numeric)

        Dim negativeNumber As Object = New DynamicNumber()

        ' Performing a mathematical negation.
        ' The TryUnaryOperation is called.
        negativeNumber = -number

        Console.WriteLine(
            negativeNumber.Textual & " " & negativeNumber.Numeric)

        '// The following statement produces a run-time exception
        '// because the unary plus operation is not implemented.
        'negativeNumber = +number
    End Sub
End Module

' This code example produces the following output:

' One 1
' Negate One -1
Platforms

Windows 7, Windows Vista, Windows XP SP2, Windows Server 2008, Windows Server 2003

The .NET Framework and .NET Compact Framework do not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.
Version Information

.NET Framework

Supported in: 4

.NET Framework Client Profile

Supported in: 4
See Also

Reference

Page view tracker