Can I override and overload the same function in vb.net? - vb.net

Is it possible to override and overload the same function at the same time in vb.net?
Something like this:
Public Overrides overloads Function Delete(ByVal code As Integer) As Boolean

You can use overloads keyword if your class contains more than one method with same name and different signature. Please see the below code and mark the answer if it's useful
Public Class Base
Public Overridable Function Delete(code As Integer) As Boolean
Return True
End Function
End Class
Public Class Derived
Inherits Base
Public Overloads Overrides Function Delete(code As Integer) As Boolean
Return MyBase.Delete(code)
End Function
Public Overloads Function Delete(code As Integer, id As Integer) As Boolean
Return MyBase.Delete(code)
End Function
End Class

No, you can't do that, because once you change the signature of the method (which would be the only reason you would want to do this), Overrides will fail to find the underlying method that you want to override.
However, you can have your override or overload call the appropriate internal method or throw an exception if the overridden version is not to be used.
Public Overrides Function Delete(ByVal code As Integer) As Boolean
Throw New Exception("Please use the two parameter version")
End Function
Public Overloads Function Delete(ByVal code As Integer, param2 As Boolean) As Boolean
MessageBox.Show("This is the right one")
Return True
End Function

It might help to think of it this way. You're asking the function to do 2 different things.
Overload calls basically the same function with a different set of parameters.
Override calls the same function with the same parameters to do something different.

Related

Interface usage within three projects

I will try to simplify as possible. In my solution i got 3 separated projects:
Main - where i use Bal
Bal - business logic, eg. classes:
Artikel
Material
Dal - data layer logic, eg. classes:
DALArtikel
DALMaterial
Now Dal's classes implements interface IDAL which looks like follows:
Public Interface IDAL
Function isExist(name As String) As Boolean
Function GetIdByName(name As String) As Integer
Function GetNameById(pId As Integer) As String
End Interface
Then i can call interface's methods from Bal's project. Every BAL's class has it's DAL class like for Artikel is DALArtikel.
Now every BAL's classes inherits from one Base class which looks like below. This Base class implements interface similar to mentioned above called IGetInformation
Public Class Base
Implements IGetInformation
Property Id As Integer
Property DAL As DataLayer.IDAL
Protected Sub New()
End Sub
Protected Sub New(dal As DataLayer.IDAL)
Me.DAL = dal
End Sub
Protected Sub New(pId As Integer)
_Id = pId
End Sub
Public Overridable Function IsExist(name As String) As Boolean Implements IGetInformation.IsExist
Return DAL.isExist(name)
End Function
Public Overridable Function GetNameById(pId As Integer) As String Implements IGetInformation.GetNameById
Return DAL.GetNameById(pId)
End Function
Public Overridable Function GetIdByName(pName As String) As Integer Implements IGetInformation.GetIdByName
Return DAL.GetIdByName(pName)
End Function
Mentioned interface:
Public Interface IGetInformation
Function isExist(name As String) As Boolean
Function GetIdByName(name As String) As Integer
Function GetNameById(pId As Integer) As String
End Interface
So every Bal's class like Artikel is constructed as following:
Public Class Artikel
Inherits Base
Property Serie As String
Property Nummer As String
Property Name As String
Sub New()
MyBase.New(New DALArtikel)
End Sub
Sub New(pId As Integer)
MyBase.New(New DALArtikel)
Id = pId
End Sub
Sub New(pId As Integer, pSerie As String)
MyBase.New(New DALArtikel)
Id = pId
Serie = pSerie
End Sub
This way i can instatiate artikel class in Main project and call it's e.g isExist method without specyfing specific DAL class associated with it as in Artikel class constructor it was already specified. The problem is now when i want to add new method which will be not in IDAL interface i have to implement like this in Artikel:
Public Function IsExistBarcode(barcode As String) As Boolean
Return New DataLayer.DALArtikel().CheckIfBarcodeExist(barcode)
End Function
so this time i have to specify DALArtikel before i call CheckIfBarcodeExist as my property DAL doesn't know it.
Generally i don't like the way as it is currently, you see that i use two separate exactly the same content interfaces for bal's and dal's projects and the logic behind. Do you know other efficient way which i could change current logic to be let's say 'better'?
Appreciate possible improvment example according to my situation. Sorry for long post but couldn't make it more less. If something unclear let me know.

Implementing Interface from C# to VB.NET

I had downloaded a C# project and wanted to work on VB.Net so I decided to convert that from C# to VB.NET and I encountered some problems when it came to implementing interfaces. I keep getting errors in VB.NET about implementation about how I must have Read-Only or Write-Only specifiers. I want to get rid of this error but I don't know how I can achieve this.
I have Three Files:
CustomPaintRichText.vb
IUnderlineableSpellingControl.vb
ISpellingControl.vb
The same goes with C#, however in C# it works fine and I want to try to get it to work exactly like that in VB.net.
CustomPaintRichText.vb:
Public Class CustomPaintRichText
Inherits RichTextBox
Implements IUnderlineableSpellingControl
Public m_underlinedSections As Dictionary(Of Integer, Integer)
Public m_protectedSections As Dictionary(Of Integer, Integer)
Public m_ignoredSections As Dictionary(Of Integer, Integer)
Public Property UnderlinedSections() As Dictionary(Of Integer, Integer)
Get
If m_underlinedSections Is Nothing Then
m_underlinedSections = New Dictionary(Of Integer, Integer)()
End If
Return m_underlinedSections
End Get
Set(value As Dictionary(Of Integer, Integer))
m_underlinedSections = value
End Set
End Property
Public WriteOnly Property ProtectedSections() As Dictionary(Of Integer, Integer)
Set(value As Dictionary(Of Integer, Integer))
m_protectedSections = value
End Set
End Property
Public WriteOnly Property IgnoredSections() As Dictionary(Of Integer, Integer)
Set(value As Dictionary(Of Integer, Integer))
m_ignoredSections = value
End Set
End Property
Private spellingEnabled As Boolean
Private spellingAutoEnabled As Boolean
Private m_isPassWordProtected As Boolean
Private penColour As Pen
Public Property WhatPenColour() As Pen
Get
Return penColour
End Get
Set(value As Pen)
penColour = value
End Set
End Property
Public Property IsSpellingEnabled() As Boolean
Get
Return spellingEnabled
End Get
Set(value As Boolean)
spellingEnabled = value
End Set
End Property
Public Property IsSpellingAutoEnabled() As Boolean
Get
Return spellingAutoEnabled
End Get
Set(value As Boolean)
spellingAutoEnabled = value
If Not spellingEnabled Then
spellingEnabled = value
End If
End Set
End Property
Public Property IsPassWordProtected() As Boolean
Get
Return m_isPassWordProtected
End Get
Set(value As Boolean)
m_isPassWordProtected = value
End Set
End Property
End Class
IUnderlineableSpellingControl.vb:
Public Interface IUnderlineableSpellingControl
Inherits ISpellingControl
Inherits IUnderlineable
End Interface
ISpellingControl.vb:
Public Interface ISpellingControl
<Browsable(True)> _
Property IsSpellingEnabled() As Boolean
Property SelectionStart() As Integer
Property SelectionLength() As Integer
Property SelectedText() As String
Property Text() As String
Property ContextMenuStrip() As ContextMenuStrip
Property WhatPenColour() As Pen
Property Parent() As Control
Event Disposed As EventHandler
Event Enter As EventHandler
Event TextChanged As EventHandler
Property [ReadOnly]() As Boolean
ReadOnly Property IsPassWordProtected() As Boolean
Sub Cut()
Sub Copy()
Sub Paste(clipFormat As DataFormats.Format)
Sub [Select](start As Integer, length As Integer)
Function Focus() As Boolean
Sub Invalidate(invalidateChildren As Boolean)
WriteOnly Property IgnoredSections() As Dictionary(Of Integer, Integer)
End Interface
If I keep the cursor carret next to Implements IUnderlineableSpellingControl and hit ENTER key, within the CustomPaintRichText.vb class, I get:
Public Property ContextMenuStrip1 As ContextMenuStrip Implements ISpellingControl.ContextMenuStrip
Public Sub Copy1() Implements ISpellingControl.Copy
End Sub
Public Sub Cut1() Implements ISpellingControl.Cut
End Sub
Public Event Disposed1(sender As Object, e As EventArgs) Implements ISpellingControl.Disposed
Public Event Enter1(sender As Object, e As EventArgs) Implements ISpellingControl.Enter
Public Function Focus1() As Boolean Implements ISpellingControl.Focus
End Function
Public WriteOnly Property IgnoredSections1 As Dictionary(Of Integer, Integer) Implements ISpellingControl.IgnoredSections
Set(value As Dictionary(Of Integer, Integer))
End Set
End Property
Public Sub Invalidate1(invalidateChildren As Boolean) Implements ISpellingControl.Invalidate
End Sub
Public ReadOnly Property IsPassWordProtected1 As Boolean Implements ISpellingControl.IsPassWordProtected
Get
End Get
End Property
Public Property IsSpellingEnabled1 As Boolean Implements ISpellingControl.IsSpellingEnabled
Public Property Parent1 As Control Implements ISpellingControl.Parent
Public Sub Paste1(clipFormat As DataFormats.Format) Implements ISpellingControl.Paste
End Sub
Public Property ReadOnly1 As Boolean Implements ISpellingControl.ReadOnly
Public Sub Select1(start As Integer, length As Integer) Implements ISpellingControl.Select
End Sub
Public Property SelectedText1 As String Implements ISpellingControl.SelectedText
Public Property SelectionLength1 As Integer Implements ISpellingControl.SelectionLength
Public Property SelectionStart1 As Integer Implements ISpellingControl.SelectionStart
Public Property Text1 As String Implements ISpellingControl.Text
Public Event TextChanged1(sender As Object, e As EventArgs) Implements ISpellingControl.TextChanged
Public Property WhatPenColour1 As Pen Implements ISpellingControl.WhatPenColour
Public Sub CustomPaint1() Implements IUnderlineable.CustomPaint
End Sub
Public Property IsSpellingAutoEnabled1 As Boolean Implements IUnderlineable.IsSpellingAutoEnabled
Public Event KeyDown1(sender As Object, e As KeyEventArgs) Implements IUnderlineable.KeyDown
Public WriteOnly Property ProtectedSections1 As Dictionary(Of Integer, Integer) Implements IUnderlineable.ProtectedSections
Set(value As Dictionary(Of Integer, Integer))
End Set
End Property
Public Sub RemoveWordFromUnderliningList1(wordStart As Integer) Implements IUnderlineable.RemoveWordFromUnderliningList
End Sub
Public Event SelectionChanged1(sender As Object, e As EventArgs) Implements IUnderlineable.SelectionChanged
Public Property UnderlinedSections1 As Dictionary(Of Integer, Integer) Implements IUnderlineable.UnderlinedSections
And when I make changes to the CustomPaintRichText from a form, I will have extra additional controls and ultimately nothing works.
The error is in Implements IUnderlineableSpellingControl. It is underlined saying that: 'CustomPaintRichText' must implement 'Event Disposed(sender As Object, e As System.EventArgs)' for interface 'ISpellingControl'. This is one of 30 errors along with the ..must implement..for interface.
Here's the error list if you want to see what kind of errors I'm getting.
Here are the .cs files in case:
CustomPaintRichText.cs
IUnderlineableSpellingControl.cs
ISpellingControl.cs
Congratulations, you made Hans Passant go "Ugh!" :)
Speaking to his point, though, mixing and matching assemblies compiled from VB, C#, C++/CLI, F#, or whatever, is generally encouraged in the .NET world, and is the practical solution to your problem. However, if you insist on transforming this C# project into its VB equivalent, one needs to understand the differences in how interfaces get implemented between these two languages.
C# has two styles of implementation: implicit and explicit (see http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx). VB has only an explicit style, which doesn't work quite the same as C# (see https://msdn.microsoft.com/en-us/library/28e2e18x.aspx).
All of those "must implement" errors mean pretty much what they say: You must use the Implements keyword on the appropriate members of your subclass, because VB doesn't do implicit implementations of interfaces. That's a C# thing. When you hit the ENTER key with the cursor caret next to Implements IUnderlineableSpellingControl, the IDE generated template code for the affected (apparently missing) members, complete with Implements. It did that in trying to be helpful, but in this case you have to look over the code and put in the Implements clauses where they're needed (and probably get rid off that template code).
C# has a neat implicit style where it will automatically "wire-up" implementations by matching member names between your class and the interfaces being implemented. Should there be more than one interface that have the same member (with the same signature), they will all be implemented with the very same member in your class (see http://blogs.msdn.com/b/mhop/archive/2006/12/12/implicit-and-explicit-interface-implementations.aspx). This can be a wonderful or not-so-good thing depending on the situation.
C# has a limited explicit style. One simply defines a member in the named in the format of InterfaceName.MemberName (see https://msdn.microsoft.com/en-us/library/ms173157.aspx).
VB has only its explicit style, but it allows for a list of interface members in the Implements clause so that they all get implemented by the very same member in your class. This is the work-around for C# implicit implementations that hookup multiple interfaces.
Finally, there are some sources which claim that VB cannot do re-implementations of an interface on a subclass of a superclass that already has it implemented (e.g. http://www.dotnetheaven.com/article/how-to-re-implement-interfaces-in-vb.net). I do not know if that was ever true, but I can aver that the VB of VS 2012 and later allows for such re-implementations.
C# allows you to implement a WriteOnly or ReadOnly property with a read/write property. (VB 2015 also allows this).
You can easily work around this prior to VB 2015 - here's an example for your IsPasswordProtected implementation:
Private ReadOnly Property ISpellingControl_IsPassWordProtected() As Boolean Implements ISpellingControl.IsPassWordProtected
Get
Return IsPassWordProtected
End Get
End Property
Public Property IsPassWordProtected() As Boolean
Get
Return isPassWordProtected_Renamed
End Get
Set(ByVal value As Boolean)
isPassWordProtected_Renamed = value
End Set
End Property
The 'Implements' goes on the new ReadOnly property which calls the existing read/write property.

Implementing inherited generic interface in vb.Net

In our current project I am using a generic interface iService which is inherited by all other service interfaces. For instance IService is inherited by ILogService.
The ILogService interface is then implemented by LogService as below:
Public Interface IService(Of T)
Sub Save(ByVal T As IEntity)
Sub Remove(ByVal T As IEntity)
Function FindBy(ByVal Id As Guid) As T
Function FindAll() As IEnumerable(Of T)
End Interface
Public Interface ILogService
Inherits IService(Of Log)
Function FindLogsByOwner(ByVal Owner As Guid, ByVal visibility As LogVisibility) As IList(Of Log)
Function FindAllLogsByVisibility(ByVal visibility As LogVisibility) As IList(Of Log)
Function FindAllLogsByType(ByVal type As LogType) As IList(Of Log)
End Interface
Public Class LogService
Implements ILogService
Public Function FindAll() As System.Collections.Generic.IEnumerable(Of Model.CSLS.Log) Implements Infrastructure.Domain.IService(Of Model.CSLS.Log).FindAll
End Function
Public Function FindBy(Id As System.Guid) As Model.CSLS.Log Implements Infrastructure.Domain.IService(Of Model.CSLS.Log).FindBy
End Function
Public Sub Remove(T As Infrastructure.Domain.IEntity) Implements Infrastructure.Domain.IService(Of Model.CSLS.Log).Remove
End Sub
Public Sub Save(T As Infrastructure.Domain.IEntity) Implements Infrastructure.Domain.IService(Of Model.CSLS.Log).Save
End Sub
Public Function FindAllLogsByType(type As Model.CSLS.LogType) As System.Collections.Generic.IList(Of Model.CSLS.Log) Implements Model.CSLS.ILogService.FindAllLogsByType
End Function
Public Function FindAllLogsByVisibility(visibility As Model.CSLS.LogVisibility) As System.Collections.Generic.IList(Of Model.CSLS.Log) Implements Model.CSLS.ILogService.FindAllLogsByVisibility
End Function
Public Function FindLogsByOwner(Owner As System.Guid, visibility As Model.CSLS.LogVisibility) As System.Collections.Generic.IList(Of Model.CSLS.Log) Implements Model.CSLS.ILogService.FindLogsByOwner
End Function
End Class
Help Needed: I am trying to understand that when I am implementing ILogService interface I still get the functions/subs in the LogService class containing:
method parameter T of Type IEntity instead of Log
How can I update the method signature so T is displayed as Log?
What am I doing wrong?
Are you talking about these?
Sub Save(ByVal T As IEntity)
Sub Remove(ByVal T As IEntity)
This is very confusing, because in the above methods T is the name of a method parameter, not a generic type parameter. It could just as easily have been foo or bar. In each case the type of T is IEntity.
If the intention here was that Save and Remove should each accept an argument of type T, but that type T must implement IEntity, this is how you would express that:
Public Interface IService(Of T As IEntity)
Sub Save(ByVal entity As T)
Sub Remove(ByVal entity As T)
Function FindBy(ByVal Id As Guid) As T
Function FindAll() As IEnumerable(Of T)
End Interface
#DanTao is correct if that is the intention. If, however, you just intended the name of the method parameter to be specified by the generic type, that is not possible.
However, you can specify any name you like in the implementing method, so you can use Log if you want, but you can't enforce it (and some FxCop rule will warn you haven't used the same parameter name as specified in the interface).

Overloads Versus Overrides in VB.net

What are the behavior differences for the Previous Property of Other1 and Other2 Class.
Note than the return type of the overloaded Previous Property of Other2 has been changed to Other2 while it stays as Base for Other1.
Public Class Base
Private _Previous as Base
Protected Overridable ReadOnly Property Previous As Base
Get
Return _Previous
End Get
End Property
Public Sub New(Previous as Base)
_Previous = Previous
End Sub
End Class
Public Class Other1
Inherits Base
Private _Parent as SomeType
Protected Overrides ReadOnly Property Previous As Base
Get
Return _Parent.Previous.Something
End Get
End Property
Public Sub New(Parent as SomeType)
MyBase.New(Nothing)
_Parent = Parent
End Sub
End Class
Public Class Other2
Inherits Base
Private _Parent as SomeType
Protected Overloads ReadOnly Property Previous As Other2
Get
Return _Parent.Previous.Something
End Get
End Property
Public Sub New(Parent as SomeType)
MyBase.New(Nothing)
_Parent = Parent
End Sub
End Class
After one of my comment to Jim Wooley's answer, "it look like it Shadows the overloaded property." I saw the light in this article.
So, the Overloads in the Other2 class act some more like shadowing than override. There is one of the comments in the article that is particularly instructive :
The confusion arises because the keyword "Overloads" isn't what a C# programmer considers an overload in the traditional OO sense. It's a type of hiding that is specific to VB.Net. You can actually swap the keyword SHADOWS with OVERLOADS in most cases, and the behavior is the same. The difference is when you have a base class with multiple overloaded method signatures. If you declare a method in a subclass with a matching name, and the SHADOWS keyword, it will hide EVERY overload of that method in the base class. If you use the OVERLOADS keyword instead, it will only hide the base class method with an identical signature.
Typically you would use Overloads when you are supplying different input parameters. Overrides replaces the functionality. In your case, you want Overrides in Other2 not Overloads. While properties can take parameters other than the value, it is best to not provide them and to use methods rather than properties when passing other values:
Public Class OldMath
Public Overridable Function DoSomething(val1 As Integer) As Integer
Return val1 + val1
End Function
End Class
Public Class NewMath
Public Overrides Function DoSomething(val1 As Integer) As Integer
Return val1 * val1
End Function
Public Overloads Function DoSomething(val1 As Integer, val2 As Integer) As Integer
Return val1 * val2
End Function
End Class
I found a great explanation on a social.msdn.microsoft.com forum.
Overloading is adding more methods to a class with the same name but different parameters.
Overriding means is replacing existing method of parent class in child class with exactly the same signature.

Custom Generic.IEqualityComparer(Of T) - Compiler Errors

I am trying to implement a simple IEqulityComparer to use with LINQ collections. I have written the following code which is reduced to its simplest form for discussion purposes...
Public Structure bob
Dim SiteID As Integer
Dim fred As String
End Structure
Public Class insCompare
Implements System.Collections.Generic.IEqualityComparer(Of bob)
Public Function Equals(ByVal x As bob, ByVal y As bob) As Boolean
Return IIf(x.SiteID = y.SiteID, True, False)
End Function
Public Function GetHashCode(ByVal x As bob) As Integer
Return x.SiteID.GetHashCode()
End Function
End Class
The problem that I have is that both functions throw the compiler warning "function 'getHashCode' (or 'Equals') shadows an overridable method in the base class 'Object'. To override the base class method, this method must be declared 'Overrides'."
However, if I declare them as Overrides, I get the error "function 'GetHashCode' cannot be declared Overrides because it does not override a function in the base class."!!
I am also getting a compiler error on the "Implements" line to the effect that I must implement "getHashCode" but I presume that is a result of the first problem.
All my research indicates that I should be ok - anyone got any clues please?
This is a late answer to the question but as per the documentation you can do use the following. Notice the inclusion of the Overloads keyword.
Public Class MyModelComparer
Implements Generic.IEqualityComparer(Of MyModel)
Public Overloads Function Equals(x As MyModel, y As MyModel) As Boolean Implements System.Collections.Generic.IEqualityComparer(Of MyModel).Equals
' do compare
End Function
Public Overloads Function GetHashCode(obj As MyModel) As Integer Implements System.Collections.Generic.IEqualityComparer(Of MyModel).GetHashCode
' do hashcode
End Function
End Class
Ok, it seems to get sorted by renaming the functions and declaring them as "Implements", although I have seen dozens of examples on the Web where this has not been the case.
However I now get a runtime exception which I will post separately.
Public Class insCompare
Implements System.Collections.Generic.IEqualityComparer(Of Object)
Public Function Equals1(ByVal x As Object, ByVal y As Object) As Boolean Implements System.Collections.Generic.IEqualityComparer(Of Object).Equals
Return IIf(x.SiteID = y.SiteID, True, False)
End Function
Public Function GetHashCode1(ByVal x As Object) As Integer Implements System.Collections.Generic.IEqualityComparer(Of Object).GetHashCode
Return x.SiteID.ToString.ToLower.GetHashCode()
End Function
End Class
I am getting same problem. I am converting my C# code to VB.Net; Even Adding the Implements didn't help;
Using a shadow or overload removes all warning and errors. I wonder what is difference in behavior in both cases.
If I specify Overrides, I get an error.
Not specifying any of (overrides, overloads, shadows) gives a warning.
' <summary>
' Pair Comparator for maintaining uniquness in results.
' </summary>
Public Class PairComparer
Implements IEqualityComparer(Of Pair)
Public Shadows Function Equals(ByVal x As Pair, ByVal y As Pair) As Boolean Implements System.Collections.Generic.IEqualityComparer(Of Pair).Equals
If x.first = y.first AndAlso x.second = y.second Then
Equals = True
ElseIf x.first = y.second AndAlso x.second = y.first Then
Equals = True
Else
Equals = False
End If
End Function
Public Overloads Function GetHashCode(ByVal obj As Pair) As Integer Implements System.Collections.Generic.IEqualityComparer(Of Pair).GetHashCode
GetHashCode = obj.first + obj.second
End Function
End Class
You're getting the compiler error because you are in VB.NET, not C#. In C#, having a method with the same signature as an interface method you need to implement makes the compiler wire it up for you automatically.
VB.NET requires that you explicitly implement say what method is being implemented. You can use the same name (it's encouraged), you just have to have that 'implements' clause.