Assigning class Instance to Interface: VB.Net

Sougata Ghosh 161 Reputation points
2021-03-07T11:15:27.683+00:00

Hello, Have two questions regarding the code below:

  1. In the following code, the class Test implement the interface Test_Interafce. I have read in more than one articles that when a class implements an interface, we should assign the class instance to the interface. Going by that in the following code the statement Dim t As New Test() should be replaced by Dim t As Test_Interface = New Test(). However I do not understand the advantage or need for the same. When I instantiate the class Test by simply writing Dim t As New Test(), I am able to access all elements (even the procedures of the interface implemented by the class) through the instance "t" and the code seems to be working fine. So then why to assign a class instance to an interface? Infact if I write Dim t As Test_Interface = New Test() then through "t" does not allow me to access the subroutine CHECK in the class Test. The error being displayed is: "CHECK is not a member of Test_Interface". So isnt that a disadvantage??!!
  2. What is the use of the statement: Throw New NotImplementedException(). This statement comes automatically when I implement teh interface in a class/structure. The code is found below: Module Module1
    Interface Test_Interface
    Function Length(ByVal s As String) As Integer
    Sub Details(ByVal age As Integer, ByVal name As String)
    End Interface
    Sub Main()
    Dim t As New Test() 'Alternate definition: Dim t As Test_Interface = New Test()
    t.Details(31, "Mounisha")
    Console.WriteLine("Length of the string entered = {0}", t.Length("Hello"))
    t.check()
    Console.ReadLine()
    End Sub
    End Module
    Class Test
    Implements Test_Interface
    Public Sub Details(age As Integer, name As String) Implements Test_Interface.Details
    Console.WriteLine("Age of person = {0}", age)
    Console.WriteLine("Name of person = {0}", name)
    'Throw New NotImplementedException() ----> what does this do?
    End Sub
    Public Function Length(s As String) As Integer Implements Test_Interface.Length
    Console.WriteLine("Original String: {0}", s)
    Return s.Length()
    'Throw New NotImplementedException()
    End Function
    Sub check()
    Console.WriteLine("The sub can be accessed")
    End Sub
    End Class
Visual Studio
Visual Studio
A family of Microsoft suites of integrated development tools for building applications for Windows, the web and mobile devices.
4,864 questions
VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,659 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 114.5K Reputation points
    2021-03-07T16:07:46.453+00:00

    One of the advantages of interfaces can be seen in the next example. If you have a definition ‘Dim t As Test_Interface’, then you can initialize t with different kinds of objects:

    Dim t As Test_Interface
    If SomeCondition Then
       t = New Test()
    Else
       t = New Test2()
    End If
    ‘ some code that deals with t
    ‘ . . .
    

    Therefore, you do not have to re-write the code for Test and Test2; the same code can be reused.

    If your CHECK function is characteristic for all of these objects, then maybe add it to interface.

    2 people found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. Xingyu Zhao-MSFT 5,361 Reputation points
    2021-03-09T02:00:02.297+00:00

    Hi @Sougata Ghosh

    Object-oriented programming is characterized by encapsulation, inheritance and polymorphism. Dim t As Test_Interface = New Test() is the embodiment of compile-time polymorphism.
    Check: VB. NET Polymorphism

    Best Regards,
    Xingyu Zhao
    *
    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Karen Payne MVP 35,386 Reputation points
    2021-03-07T12:23:51.03+00:00

    Hello,

    Visual Studio IDE inserts NotImplementedException by default which indicates the method does nothing and that the developer needs to write code for the method. If not ready at the time of implementing a method for the interface and want to call the method simple delete Throw New NotImplementedException() from the method.

    In regards to creating an instance of a class which implements an Interface, you should create the class instance as recommended by Microsoft see this page.

    Friend Interface ISampleInterface  
        Sub SampleMethod()  
    End Interface  
      
    Friend Class ImplementationClass  
        Implements ISampleInterface  
      
        ' Explicit interface member implementation:  
        Private Sub ISampleInterface_SampleMethod() Implements ISampleInterface.SampleMethod  
            ' Method implementation.  
        End Sub  
      
        Shared Sub Main()  
            ' Declare an interface instance.  
            Dim obj As ISampleInterface = New ImplementationClass()  
      
            ' Call the member.  
            obj.SampleMethod()  
        End Sub  
    End Class  
    

    Going back to your code. I've modified your code.

    • When creating an Interface the naming convention is upper case I as the first character followed by a name where the first character is upper cased.
    • Avoid single character variable and parameter names
    • Demo how to determine if a object implements an interface and cast to it if it does.

    75073-f1.png

    Module Program  
        Sub Main(args As String())  
      
            Dim tester As New Test()  
      
            DoesObjectImplementITestInterface(tester)  
      
            Console.WriteLine($"Length of the string entered = {tester.Length("Hello")}")  
            tester.Check()  
      
            Console.ReadLine()  
      
        End Sub  
        Sub DoesObjectImplementITestInterface(sender As Object)  
      
            If TypeOf sender Is ITestInterface Then  
                Console.ForegroundColor = ConsoleColor.Yellow  
                CType(sender, ITestInterface).Details(55, "Some name")  
            Else  
                Console.ForegroundColor = ConsoleColor.Red  
                Console.WriteLine("No")  
            End If  
      
            Console.ResetColor()  
      
        End Sub  
    End Module  
    Module Module1  
        Interface ITestInterface  
            Function Length(value As String) As Integer  
            Sub Details(age As Integer, ByVal name As String)  
        End Interface  
    End Module  
    Class Test  
        Implements ITestInterface  
      
        Public Sub Details(age As Integer, name As String) Implements ITestInterface.Details  
            Console.WriteLine($"Age of person = {age}")  
            Console.WriteLine($"Name of person = {name}")  
        End Sub  
      
        Public Function Length(value As String) As Integer Implements ITestInterface.Length  
            Console.WriteLine($"Original String: {value}")  
            Return value.Length()  
        End Function  
      
        Sub Check()  
            Console.WriteLine("The sub can be accessed")  
        End Sub  
      
    End Class  
    
    1 person found this answer helpful.
    0 comments No comments