Open sandboxFocus

Method CreateDelegateExpression

CreateDelegateExpression(INamedType?)

Creates an IExpression that represents the current method as a delegate.

Declaration
IExpression CreateDelegateExpression(INamedType? delegateType = null)
Parameters
Type Name Description
INamedType delegateType

An optional delegate type to use for disambiguation when the method has overloads. When specified, this type is used to wrap the method group expression (e.g. new MyDelegate(this.Method)), regardless of the target type context. No compatibility verification is performed between the method's signature and the specified delegate type — any mismatch will result in a C# compilation error in the generated code.

Returns
Type Description
IExpression

An IExpression whose Value represents a delegate pointing to the current method.

Remarks

When the method has no overloads and no delegateType is specified, this generates a simple method group expression (e.g. this.Method).

When the method has overloads, the generated code depends on the delegateType and the target type context:

  • If delegateType is specified, it is used to select the appropriate overload. The generated expression may use an explicit delegate-construction expression (e.g. new MyDelegate(this.Method)) or a bare method group when the surrounding target typing already enforces the same delegate type.
  • If the expression is assigned to a variable of a specific delegate type (e.g. EventHandler, or a custom delegate), and that delegate type is compatible with the method's signature, the target delegate type is used for disambiguation. The resulting code may similarly be either an explicit delegate-construction expression or a bare method group, depending on what is required by the C# compiler to resolve the overload.
  • Otherwise, Action<> or Func<> is used for disambiguation (e.g. new Action<int>(this.Method)).

If the method has overloads and its signature contains out, in, or ref parameters, and neither delegateType nor a compatible target delegate type is available, an exception is thrown because Action<>/Func<> cannot represent such signatures.

By default, the delegate references the method on the current object (this), unless the method is static. Use WithObject(dynamic?) to specify a different target instance before calling this method.