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
- 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
Interface Encryption End Interface
- 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
- If the interface you are implementing is not part of your project, add a reference to the assembly containing the interface.
- 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
Encryptioninterface using Xor encryption, you could name the implementation class
XorEnc, as in the following code:
Class XorEnc Implements Encryption End Class
- 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.
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