Search code examples
vb.netenumsoptional-parametersenumerable

Passing an optional Enum to a function in VB.NET


I am trying to pass an optional Enum to a function but can't get the syntax right. I am trying the following:

Public Function MyFunction(ByVal TestCode As String, Optional ByVal Columns As [Enum] = MyEnumName.EnumVariable) As Boolean

Also tried:

Public Function MyFunction(ByVal TestCode As String, Optional ByVal Columns As [Enum] = MyEnumName) As Boolean

And get the error message

"Conversion from "MyEnumName" to "System.Enum" cannot occur in a constant expression"

Is it possible to have optional Enums or what am I doing wrong?

Thanks in advance


Solution

  • When dealing with Enums, you have to specify as type the given name rather than [Enum]. Sample code:

    Public Enum MyEnumName
        val1
        val2
    End Enum
    
    Public Function MyFunction(ByVal TestCode As String, Optional ByVal Columns As MyEnumName = MyEnumName.val1) As Boolean
    
    End Function