Home > OS >  Can you specify a default value for a function or sub parameter of type Func or Action?
Can you specify a default value for a function or sub parameter of type Func or Action?

Time:06-13

Consider the following code (don't mind the design, it's just an example):

Private _value As Boolean

Public Sub SetValue(Optional getValue As Func(Of Boolean) = ... )
    _value = getValue()
End Sub

How can I get this to work without using Nothing ?
For the sake of simplicity let's say I want the default value to be a function that always returns True. Can it be done? If so, can it be done inline?

Thanks in advance !

CodePudding user response:

Default values for optional parameters must be constant expressions (source).

In .NET, you can only have constants of “primitive types” (Boolean, Byte, Char, DateTime, Decimal, Double, Integer, Long, Short, Single, or String, source).

So you cannot use a function reference as a default value.

As a workaround, you can use:

Private _value As Boolean

Public Sub SetValue(Optional getValue As Func(Of Boolean) = Nothing )
    _value = If(getValue(), DefaultFunc())
End Sub

Or you could use an overload:


Private _value As Boolean

Public Sub SetValue(getValue As Func(Of Boolean))
    _value = getValue()
End Sub

Public Sub SetValue()
    _value = GetDefaultValue()
End Sub

  • Related