Justin
Justin

Reputation: 23

Creating A Named Function Parameter Array

Is it possible to create a routine in VB.NET with a name-based parameter array?

The WebMethod attribute built into the framework is used exactly this way:

  WebMethod(BufferResponse:=False)

Specifically, I'd like to use it in a class' constructor. I'd like something similar to this:

  New MyObject(id:=10,buffer:=True)

I'm not even sure what the terminology is for this kind of parameter list, so I can't even find it when searching.

Upvotes: 1

Views: 434

Answers (2)

MarkJ
MarkJ

Reputation: 30398

You don't need to do anything special in the definition of MyObject. Just go straight ahead and type New MyObject(id:=10,buffer:=True), assuming that the constructor has parameters called id and buffer. This means you can type the parameters in any order, you don't have to use the order in the declaration. See the VB manual.

Personally I think this named parameter style is a bit old-fashioned, and it will make it hard for other developers to read your code, unless they're old like me and remember VB6. The style was common in VB6 with optional parameters, but IMHO (and according to Microsoft) in VB.Net overloading is usually more elegant than optional parameters.

Upvotes: 0

Chris Haas
Chris Haas

Reputation: 55427

Are you trying to create an object from scratch or does there already exist a class definition already? If the class exists you can use either named parameters in the constructor with default parameters:

Public Class TestClass
    Public Property A As Integer
    Public Property B As Integer
    Public Sub New(Optional ByVal a As Integer = -1, Optional ByVal b As Integer = -1)
        Me.A = a
        Me.B = b
    End Sub
End Class

Dim Obj As New TestClass(b:=2)

There's also object initialization:

Dim Obj As New TestClass() With {.A = 2}

Or are you trying to create a generic object like in Javascript/JSON? Like:

var obj = new Object();
obj.MyProp = 27;

This type of syntax doesn't exist for VB

Upvotes: 2

Related Questions