Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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 !

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading