Reputation: 11419
I would like to make multiple subs with the same name but with different parameters.
For example:
Public Sub DoThis(Byval CustomerName As String)
Public Sub DoThis(Byval CustomerID As Integer)
Public Sub DoThis(Byval CustomerID As Integer, ReferenceID As Integer)
But then VB.NET is telling me that such a sub already exists. Can somebody please tell me how I can do this?
Thank you!
Upvotes: 2
Views: 4748
Reputation: 117
Been a while since I did VB .NET but I think you need to add the Overloads key word, so it will become:
Public Overloads Sub DoThis(Byval CustomerName As String)
Public Overloads Sub DoThis(Byval CustomerID As Integer)
Public Overloads Sub DoThis(Byval CustomerID As Integer, ReferenceID As Integer)
Upvotes: 1
Reputation: 546143
What you’ve shown us absolutely works – VB won’t complain about this.
This is called Overloading and it’s an essential feature of .NET. However, in order for this to work you need to make sure that the signatures (i.e. the parameter type lists) are strictly distinct for all your overloads.
Here’s an example to showcase the importance of distinct parameter type lists:
Sub DoThis(CustomerName As String) …
Sub DoThis(ProductName As String) …
The subs look distinct. But how should VB handle the following call?
DoThis("Meyer")
It cannot know whether “Meyer” is a customer name or a product name (in fact, it could well be either!) – so VB forbids these declarations. However, the following is absolutely fine, because unambiguous:
Sub DoThis(Customer As Customer)
Sub DoThis(Product As Product)
DoThis(New Customer("Meyer"))
Upvotes: 7