Question

This is a cousin of the question "Can CodeDom create optional arguments when generating a c# method?"

And I tried the answer given there.

Still, when I attempt to compile, I get the following error:

error BC30455: Argument not specified for parameter 'optionalParam' of 'Public Function Bar(optionalParam As Integer) As Integer

I've distilled this down to the Visual Basic Compiler not supporting either OptionalAttribute, DefaultParameterValueAttribute, or both.

Here's the distilled code I'm compiling:

Imports System.Runtime.InteropServices

Namespace SSI.RuntimeGenerated.FunctionsNamespace
    Public Class Functions
        Public Function Foo() As Integer

            return Bar()

        End Function

        Public Function Bar( _
            <[Optional], DefaultParameterValue(1)> _
            ByVal optionalParam As Integer) _
                As Integer

            return optionalParam

        End Function

    End Class
End Namespace

Compiling this with the following command:

"C:\Windows\Microsoft.NET\Framework\v4.0.30319\vbc.exe" /t:library /out:foobar.dll foobar.vb /langversion:11

Produces the following output:

Microsoft (R) Visual Basic Compiler version 11.0.50709.17929
Copyright (c) Microsoft Corporation All rights reserved.

C:\<snip>\foobar.vb : error BC30455: Argument not specified for parameter
'optionalParam' of 'Public Function Bar(optionalParam As Integer) As Integer'.
            return Bar()
                   ~~~~~

If I change the method signature manually to be

Public Function Bar(Optional ByVal optionalParam As Integer) As Integer

then it compiles just fine.

So my questions are:

  1. How to create optional arguments in Visual Basic generated through CodeDom?
  2. Does vbc even support use of OptionalAttribute and/or DefaultParameterValueAttribute?
  3. If vbc doesn't support those attributes, is there any possible way to create Optional arguments without resorting to using a CodeSnippetStatement?
  4. If there's no other way, then is it possible to salvage other work I've done with CodeDom so I don't end up having to pretty much generate my methods by hand? Do I have to pretty much build the rest by hand inside a CodeSnippetTypeMember? Would even that work?
Was it helpful?

Solution

The OptionalAttribute is not supported in VB.NET. I cannot find any official documentation that specifically says so, but if you try to use it in a VB.NET project, it will have no effect. To create an optional parameter in VB.NET, you must use the Optional keyword, for instace:

Public Class Functions
    Public Function Foo() As Integer
        Return Bar()
    End Function

    Public Function Bar(Optional ByVal optionalParam As Integer = 1) As Integer
        Return optionalParam
    End Function
End Class
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top