Search code examples
vb.netattributesnamed-parameters

Named parameters with attribute constructors


Reading the documentation on using attributes: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/concepts/attributes/, and it says that named parameters are allowed. I read that that as named parameters to the constructor, but that doesn't seem to work:

Public Class FullName
    Inherits System.Attribute
    Public Property Name As String
    Public Property Hey As String
    Sub New(FirstName As String, LastName As String)
        Name = FirstName + " " + LastName
    End Sub
End Class

<FullName(LastName:="moreno", FirstName:="John", Hey:="joe")>
Public Class Example
   Public Sub Test
      Dim x = New FullName(LastName:="moreno", FirstName:="john")
   End Sub 
End Class

Do attributes not support named parameters for the constructor in vb, or am I just missing the right syntax?


Solution

  • The actual constructor parameters do not get named. Named parameters are for setting properties. You can think of it as being much like an object initialiser in regular code:

    Dim fn As New FullName("John", "moreno") With {.Hey = "joe"}
    
    <FullName("John", "moreno", Hey:="joe")>
    

    The constructor parameters are the positional parameters referred to in that documentation and then named parameters are properties that you may or may not set.