Pages

Sunday, March 18, 2012

Overriding the ToString Method


Every class and object includes the ToString method. By default, this returns a string containing the name of your custom class or structure. By overriding this method, you can return more meaningful, human-readable information about your objects.
Every object  gets the ToString method, which returns a string representation of that object. For example, all variables of type int have a ToString method, which enables them to return their contents as a string.
All classes and structures are based upon the Object class, so every such item that you define automatically inherits the ToString method
Lets us look into one simple example.



'''

''' Class which do some kind of calculation.
''' This class has overrided ToString method
'''

'''
Public Class Calculate 
    ' Private property which will be used inside this class
    Private m_OutPutValue As Integer
    Private Property OutPutValue() As Integer
        Get
            Return m_OutPutValue
        End Get
        Set(ByVal value As Integer)
            m_OutPutValue = value
        End Set
    End Property

    ' Public constructor of the class.
    ' In this constructor we set the value of outputValue property
    Public Sub New(ByVal x As Integer, ByVal y As Integer)
        OutPutValue = x + y
    End Sub

    ' Tostring method has been overrides to return the OutputValue as string.
    Public Overrides Function ToString() As String
        '
        '   Logic of this calculate class.
        ' 
        ' Return the value as string.
        Return Me.OutPutValue.ToString()
    End Function
End Class

Public Class Form1 
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load 
        ' Instance of Calculate Class is created
        Dim obj As New Calculate(30, 20)
        ' Here obj.tostring will return the, value of calculate class, instead of class name.
        MessageBox.Show(obj.ToString())
    End Sub
End Class

No comments: