|
In previous lessons, we learned that, to convert the value of a variable declared from a primitive type to a string, you could call the ToString() function. Here is an example: Imports System
Module Exercise
Public Function Main() As Integer
Dim NumberOfPages As Integer = 422
Console.Write("Number of Pages: ")
Console.WriteLine(NumberOfPages.ToString())
Return 0
End Function
End Module
In many programming languages, programmers usually have to overload an (extractor) operator to display the value(s) of class' variable to the screen. The Object class provides an alternative to this somewhat complicated solution, through the ToString() method. It syntax is: Public Overridable Function ToString As String Although the Object class provides this method as non abstract, its implemented version is more useful if you use a primitive type such as Integer, Double and their variances or a string variable. The best way to rely on it consists of overriding it in your own class if you desire to use its role.
When we study inheritance, we will learn that all data types used in a C# program are "based on" an object called object. As introduced earlier, you can use this data type to declare a variable that would hold any type of value. Because this is some type of a "universal" data type, it can also be initialized with any value. Here are examples: Imports System
Module Exercise
Public Function Main() As Integer
Dim Number As Object
Dim Thing As Object
Number = 244
Thing = "Professor Kabba"
Console.WriteLine(Number)
Console.WriteLine(Thing)
Return 0
End Function
End Module
This would produce: 244 Professor Kabba As you can see, when an object variable is initialized, the compiler finds out the type of value that was assigned to it. This is referred to as boxing. This mechanism is transparently done in Visual Basic. If you declare a variable using a primitive data type (Integer, Single, Double, etc), at one time, you may be interested in converting the value of that variable into an Object. Here is an example: Imports System
Module Exercise
Public Function Main() As Integer
Dim Number As Integer = 244
Dim Thing As Object = Number
Number = 244
Thing = Number
Console.WriteLine(Number)
Console.WriteLine(Thing)
Return 0
End Function
End Module
This would produce: 244 244 This operation is referred to as unboxing. As you can see, this operation is performed transparently.
While a constructor, created for each class, is used to instantiate a class. The Object class provides the Finalize() method as a type of destructor. |
|
|||||||
|
|