Reputation: 306
Suppose i have:
Public Class clsTest
Public Sub New()
End Sub
Public Sub New(name_ As String)
'...
End Sub
End Class
I want to expand this class such:
<System.Runtime.CompilerServices.Extension> _
Public Sub methodA(t1 As clsTest, i As Integer)
'...
End Sub
But i can not extend constructor as:
<System.Runtime.CompilerServices.Extension> _
Public Sub New(t1 As clsTest, name_ As String, i As Integer)
'...
End Sub
Upvotes: 1
Views: 3625
Reputation: 460340
You cannot extend constructors with an extension method. An extension method is nearly the same as a static
(shared
in VB) method that allows to write
instanceOfMyClass.SomeExtension(someParameter)
instead of
MyClass.SomeExtension(instanceOfMyClass, someParameter)
If you don't have acces to clsTest
(you should really change your namings) but you want to extend it anyway, you could also create a new class that inherits from it:
Public Class Foo ' consider this as your clsTest
Public Sub New()
End Sub
Public Property Name As String
Public Property Number As Int32
Public Sub New(name As String)
Me.Name = Name
End Sub
End Class
Public Class Bar
Inherits Foo
Public Sub New(name As String, i As Integer)
MyBase.Name = name
MyBase.Number = i
End Sub
End Class
Finally, maybe you don't need to extend the class but you're just looking for a convenient way to initialize it in an one-liner:
Dim foo = New Foo("test") With {.Number = 4711}
Upvotes: 3