Export (0) Print
Expand All

Creating and Implementing an Interface

As explained in Interfaces Overview, interfaces describe the properties, methods, and events of a class without providing any implementation.

To create an interface

  1. Define your interface by adding code to it that begins with the Interface keyword and the name of the interface, and ends with the End Interface statement. For example, the following code defines an interface named Encryption:
    Interface Encryption
    End Interface
    
  2. Add statements that define the properties, methods, and events your interface supports. For example, the following code defines two methods, a property, and an event:
    Interface Encryption
       Function Encrypt(ByVal estring As String) As String
       Function Decrypt(ByVal dstring As String) As String
       Property EncryptionBits() As Integer
       Event FinishedDecoding(ByVal RetVal As Integer)
    End Interface
    

To implement an interface

  1. If the interface you are implementing is not part of your project, add a reference to the assembly containing the interface.
  2. Create a new class that implements your interface, and include the Implements keyword in the line following the class name. For example, to implement the Encryption interface using Xor encryption, you could name the implementation class XorEnc, as in the following code:
    Class XorEnc
       Implements Encryption
    End Class
    
  3. Add procedures to implement the properties, methods, and events of the class as in the following code, which builds on the example in the previous step:
    Class XorEnc
       Implements Encryption
       Event FinishedDecoding(ByVal RetVal As Integer) _ 
          Implements Encryption.FinishedDecoding
    
       Function Encrypt(ByVal estring As String) _
          As String Implements Encryption.Encrypt
          ' Place code to perform Xor encryption here.
       End Function
       Function Decrypt(ByVal dstring As String) _
          As String Implements Encryption.Decrypt
          ' Place code to perform Xor decryption here.
       End Function
            
       Property EncryptionBits() As Integer _
          Implements Encryption.EncryptionBits
          Get
             'Place code to return the value of this property here.
          End Get
          Set
             'Place code to set this property here.
          End Set
       End Property
    End Class
    
    Note   This walkthrough uses simple Xor encryption to demonstrate interface implementation. You should use a more sophisticated form of encryption to store sensitive information.

See Also

Interfaces Overview | Interface Definition | Interface Statement | Implements Keyword | Interface Implementation Examples | When To Use Interfaces | Creating and Implementing an Interface | Walkthrough: Creating and Implementing Interfaces | Inheritance | Xor Operator

Show:
© 2014 Microsoft