- INDEX VB TO NET
- VBUC FEATURES
- LANGUAGE TRANSFORMATIONS
- INTERFACES SUPPORT
- USING POLYMORPHISM
Using Polymorphism
Polymorphism is a feature of object-oriented languages that allows values of different data types to be handled using a uniform interface. Visual Basic 6 provides this feature of object-oriented languages by implementing interfaces.
By the way, an interface can be instantiated with several different classes that implement the interface, and it can polymorphically access the members of the class instances.
The classes and interfaces in this case are upgraded as indicated in the sections above. The issue in this case is the creation process for instances. If you create an instance of the target interface, the variable must be declared as the interface type, but the instance must be of CoClass class, which has the original implementation. In case of a creation of an implementing class, the variable must be declared and instanced in the same class type. An important observation is that a variable of the interface type could be changed to any of the implementing class types.
In the following example, there is an interface (Animal) and two implementing classes (Dog and Bird).
Original VB6 code
Private anAnimal As Animal Private anAnimal2 As New Animal Private Function BirdName() As String Set anAnimal = New Bird BirdName = anAnimal.Name End Sub
VBUC resulting VB.NET code
Private anAnimal As Animal Private _anAnimal2 As Animal = Nothing Private Property anAnimal2() As Animal Get If _anAnimal2 Is Nothing Then _anAnimal2 = New Animal_CoClass End If Return _anAnimal2 End Get Set(ByVal Value As Animal) _anAnimal2 = value End Set End Property Private Function BirdName () As String anAnimal = New Bird Return anAnimal.Name End Sub
VBUC resulting C#.NET code
private Animal anAnimal = null; private Animal _anAnimal2 = null; private Animal anAnimal2 { get { if (_anAnimal2 == null) { _anAnimal2 = new Animal_CoClass(); } return _anAnimal2; } set { _anAnimal2 = value; } } private string BirdName() { anAnimal = new Bird(); return anAnimal.Name; }