Home
VB.NET
ToString, Overrides Example
This page was last reviewed on Jun 12, 2023.
Dot Net Perls
ToString. We can provide a custom ToString function on a VB.NET class. By using an Overrides ToString function, we specify how an instance renders itself as a String.
Overrides note. ToString() should use the Overrides modifier. This will cause it to be used as the implementation for less derived type references such as Object.
This program introduces the Perl class. This class, by default, inherits from the Object class. On the Object class (not shown) there exists an Overridable Function ToString.
Note The Perl class here provides the implementation that overrides ToString.
Info When Perl is used as an Object, its custom ToString implementation is still used.
Here When we construct the Perl instance, its fields are set to 2 and 3. It is passed to the Console.WriteLine subroutine as an Object.
Finally In Console.WriteLine, the ToString function is called on that Object. The Overrides Function ToString implementation is used.
Console.WriteLine
Module Module1 Class Perl Dim _a As Integer Dim _b As Integer Public Sub New(ByVal a As Integer, ByVal b As Integer) _a = a _b = b End Sub Public Overrides Function ToString() As String Return String.Format("[{0}, {1}]", _a, _b) End Function End Class Sub Main() Dim p As Perl = New Perl(2, 3) Console.WriteLine(p) End Sub End Module
[2, 3]
A discussion. In the VB.NET language, we see Overridable functions and Overrides functions. These are equivalent to virtual and override methods in the C# language.
Detail The term "overridable" may be a clearer description of a virtual function. The term virtual is less obvious.
Function
Sub
We looked at how you can provide the ToString function in your VB.NET program. This function returns a String. You can use any logic you wish to construct the String.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 12, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.