Delen via


'Optional' cannot be applied to the first parameter of an extension method

'Optional' cannot be applied to the first parameter of an extension method. The first parameter specifies which type to extend.

The first parameter of an extension method specifies the data type that the method extends. When the method is executed, the first parameter is bound to the instance of the data type that invokes the method. Therefore, the first parameter is required and cannot be optional.

The restriction applies only to the first parameter. Other parameters can be optional or not, following the same rules as in any other method. For more information, see Parameter List.

Error ID: BC36553

To correct this error

  • If you want the current first parameter to specify the data type being extended, remove the Optional keyword.

  • If the current first parameter is a standard parameter to the method and you do not want it to represent the data type being extended, add a new first parameter.

Example

The first parameter in the following example is the only indication that the Print method extends the String data type. Therefore, it cannot be optional.

<Extension()>
Public Sub Print (ByVal str As String)
    Console.WriteLine(str)
End Sub

When the extension method is called as follows, parameter str in the method is bound to greeting, the instance of String that calls Print. The compiler uses greeting as the argument to extension method Print.

    Dim greeting As String = "Hello"
    greeting.Print()

See Also

Tasks

How to: Define Optional Parameters for a Procedure

Concepts

Extension Methods (Visual Basic)

Optional Parameters