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

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

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

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

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

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

Parameters

binder
Type: System.Dynamic..::.BinaryOperationBinder
Provides information about the type of the binary operation. The binder.Operation property returns an object of the ExpressionType type. For example, for the sum = first + second statement, where first and second are derived from the DynamicObject class, binder.Operations returns "Add".
arg
Type: System..::.Object
The right operand for the binary operation. For example, for the sum = first + second statement, where first and second are derived from the DynamicObject class, arg is equal to second.
result
Type: System..::.Object%
The result of the binary 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 binary 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 binary operations such as addition or multiplication. For example, if the TryBinaryOperation method is overridden, it is automatically invoked for statements like sum = first + second or multiply = first*second, where first and second are derived from the DynamicObject class.

You can get information about the type of the binary 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

Add

An arithmetic addition operation without overflow checking.

a + b

a + b

AddAssign

An arithmetic addition compound assignment operation without overflow checking.

a += b

Not supported.

And

A bitwise AND operation.

a & b

a And b

AndAssign

A bitwise AND compound assignment operation.

a &= b

Not supported.

Divide

An arithmetic division operation.

a / b

a / b

DivideAssign

An arithmetic division compound assignment operation.

a /= b

Not supported.

ExclusiveOr

A bitwise XOR operation.

a ^ b

a Xor b

ExclusiveOrAssign

A bitwise XOR compound assignment operation.

a ^= b

Not supported.

GreaterThan

A "greater than" numeric comparison.

a > b

a > b

GreaterThanOrEqual

A "greater than or equal to" numeric comparison.

a >= b

Not supported.

LeftShift

A bitwise left-shift operation.

a << b

a << b

LeftShiftAssign

A bitwise left-shift compound assignment operation.

a <<= b

Not supported.

LessThan

A "less than" numeric comparison.

a < b

a < b

LessThanOrEqual

A "less than or equal to" numeric comparison.

a <= b

Not supported.

Modulo

An arithmetic remainder operation.

a % b

a Mod b

ModuloAssign

An arithmetic remainder compound assignment operation.

a %= b

Not supported.

Multiply

An arithmetic multiplication operation without overflow checking.

a * b

a * b

MultiplyAssign

An arithmetic multiplication compound assignment operation without overflow checking.

a *= b

Not supported.

NotEqual

An inequality comparison.

a != b

a <> b

Or

A bitwise OR operation.

a | b

a Or b

OrAssign

A bitwise OR compound assignment.

a |= b

Not supported.

Power

A mathematical operation of raising a number to a power.

Not supported.

a ^ b

RightShift

A bitwise right-shift operation.

a >> b

a >> b

RightShiftAssign

A bitwise right-shift compound assignment operation.

a >>= b

Not supported.

Subtract

An arithmetic subtraction operation without overflow checking.

a - b

a - b

SubtractAssign

An arithmetic subtraction compound assignment operation without overflow checking.

a -= b

Not supported.

Examples

Assume that you need a data structure to store textual and numeric representations of numbers, and you want to define basic mathematical operations such as addition and subtraction for such data.

The following code example demonstrates the DynamicNumber class, which is derived from the DynamicObject class. DynamicNumber overrides the TryBinaryOperation method to enable mathematical operations. It also overrides the TrySetMember and TryGetMember methods to enable access to the elements.

In this example, only addition and subtraction operations are supported. If you try to write a statement like resultNumber = firstNumber*secondNumber, a run-time exception is thrown.

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 binary operation. 
    public override bool TryBinaryOperation(
        BinaryOperationBinder binder, object arg, out object result)
    {
        // The Textual property contains the textual representaion 
        // of two numbers, in addition to the name 
        // of the binary operation.
        string resultTextual =
            dictionary["Textual"].ToString() + " "
            + binder.Operation + " " +
            ((DynamicNumber)arg).dictionary["Textual"].ToString();

        int resultNumeric;

        // Checking what type of operation is being performed.
        switch (binder.Operation)
        {
            // Proccessing mathematical addition (a + b).
            case ExpressionType.Add:
                resultNumeric =
                    (int)dictionary["Numeric"] +  
                    (int)((DynamicNumber)arg).dictionary["Numeric"];
                break;

            // Processing mathematical substraction (a - b).
            case ExpressionType.Subtract:
                resultNumeric =
                    (int)dictionary["Numeric"] - 
                    (int)((DynamicNumber)arg).dictionary["Numeric"];
                break;

            // In case of any other binary 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.)
            default:
                Console.WriteLine(
                    binder.Operation + 
                    ": This binary 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 firstNumber = new DynamicNumber();

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

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

        // Creating the second dynamic number.
        dynamic secondNumber = new DynamicNumber();       
        secondNumber.Textual = "Two";
        secondNumber.Numeric = 2;
        Console.WriteLine(
            secondNumber.Textual + " " + secondNumber.Numeric);
       

        dynamic resultNumber = new DynamicNumber();

        // Adding two numbers. The TryBinaryOperation is called.
        resultNumber = firstNumber + secondNumber;

        Console.WriteLine(
            resultNumber.Textual + " " + resultNumber.Numeric);

        // Subtracting two numbers. TryBinaryOperation is called.
        resultNumber = firstNumber - secondNumber;

        Console.WriteLine(
            resultNumber.Textual + " " + resultNumber.Numeric);

        // The following statement produces a run-time exception
        // because the multiplication operation is not implemented.
        // resultNumber = firstNumber * secondNumber;
    }
}

// This code example produces the following output:

// One 1
// Two 2
// One Add Two 3
// One Subtract Two -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 binary operation. 
    Public Overrides Function TryBinaryOperation(
        ByVal binder As System.Dynamic.BinaryOperationBinder, 
        ByVal arg As Object, ByRef result As Object) As Boolean

        ' The Textual property contains the textual representaion 
        ' of two numbers, in addition to the name of the binary operation.
        Dim resultTextual As String =
            dictionary("Textual") & " " &
            binder.Operation.ToString() & " " &
        CType(arg, DynamicNumber).dictionary("Textual")

        Dim resultNumeric As Integer

        ' Checking what type of operation is being performed.
        Select Case binder.Operation
            ' Proccessing mathematical addition (a + b).
            Case ExpressionType.Add
                resultNumeric =
                CInt(dictionary("Numeric")) +
                CInt((CType(arg, DynamicNumber)).dictionary("Numeric"))

                ' Processing mathematical substraction (a - b).
            Case ExpressionType.Subtract
                resultNumeric =
                CInt(dictionary("Numeric")) -
                CInt((CType(arg, DynamicNumber)).dictionary("Numeric"))
                
            Case Else
                ' In case of any other binary 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 binary 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 firstNumber As Object = New DynamicNumber()

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

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

        ' Creating the second dynamic number.
        Dim secondNumber As Object = New DynamicNumber()
        secondNumber.Textual = "Two"
        secondNumber.Numeric = 2
        Console.WriteLine(
            secondNumber.Textual & " " & secondNumber.Numeric)

        Dim resultNumber As Object = New DynamicNumber()

        ' Adding two numbers. TryBinaryOperation is called.
        resultNumber = firstNumber + secondNumber
        Console.WriteLine(
            resultNumber.Textual & " " & resultNumber.Numeric)

        ' Subtracting two numbers. TryBinaryOperation is called.
        resultNumber = firstNumber - secondNumber
        Console.WriteLine(
            resultNumber.Textual & " " & resultNumber.Numeric)

        ' The following statement produces a run-time exception
        ' because the multiplication operation is not implemented.
        ' resultNumber = firstNumber * secondNumber
    End Sub
End Module

' This code example produces the following output:

' One 1
' Two 2
' One Add Two 3
' One Subtract Two -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