This documentation is archived and is not being maintained.

11.10.3 Delegate-Creation Expressions

Visual Studio .NET 2003

A delegate-creation expression is used to create a new instance of a delegate type. The argument of a delegate-creation expression must be an expression classified as a method pointer.

One of the methods referenced by the method pointer must exactly match the signature of the delegate type. A method matches the delegate type if the method is not declared MustOverride and if both their signatures and return types match. In the following example, the A.f variable is initialized with a delegate that refers to the second Square method because that method exactly matches the signature and return type of DoubleFunc.

Delegate Function DoubleFunc(x As Double) As Double
Class A
    Private f As New DoubleFunc(AddressOf Square)
    Overloads Shared Function Square(x As Single) As Single
        Return x * x
    End Function 
    Overloads Shared Function Square(x As Double) As Double
        Return x * x
    End Function 
End Class

Had the second Square method not been present, a compile-time error would have occurred.

The result of the expression is a delegate instance that refers to the matching method with the associated instance expression (if any) from the method pointer expression. If the instance expression is typed as a value type, then the value type is copied onto the system heap because a delegate can only point to a method of an object on the heap. The method and object to which a delegate refers remain constant for the entire lifetime of the delegate. In other words, it is not possible to change the target or object of a delegate after it has been created.

DelegateCreationExpression ::= New TypeName ( Expression )

See Also

11.10.1 Object-Creation Expressions | 11.10.2 Array-Creation Expressions | 11.10 New Expressions | New (Visual Basic Language Reference) | Using the New Keyword (Visual Basic Language Concepts)

Show: