+92 332 4229 857 99ProjectIdeas@Gmail.com

A Complete Class Example (Vb.net)



The following code shows you a complete class example... declaring variables, setter and getters, constructors and methods related to class.
Declaring class objects in Main(). accessing private members of class. etc etc...






Public Class MyFirstClass

    Private _Name As String = Nothing

    'Setter and Getter Of _Name variable
    Public Property Name() As String
        Get
            Return _Name
        End Get
        Set(ByVal value As String)
            _Name = value
        End Set
    End Property

    Private _age As Integer = Nothing

   'Setter and Getter Of _age variable, if it is greater than zero
    Public Property Age() As Integer
        Get
            Return _age
        End Get
        Set(ByVal value As Integer)
            If value > 0 Then
                _age = value
            End If
        End Set
    End Property

    Private _countryName As String = Nothing
   
    'Setters and Getters of _countryName variable
    Public Property CountryName() As String
        Get
            Return _countryName
        End Get
        Set(ByVal value As String)
            _countryName = value
        End Set
    End Property

    ' Declaring Constructor with zero arguments
    Sub New()

        Name = String.Empty
        Age = 0
        CountryName = String.Empty

    End Sub

    ' Declaring Parameterized Constructor
    Sub New(ByVal n As String, ByVal c As String, ByVal a As Integer)

        Me.Name = n
        Me.Age = a
        Me.CountryName = c

    End Sub

    ' A method to display
    Public Sub Display()

        Console.WriteLine("The Name Of Person Is : " & Name)
        Console.WriteLine("The Age Of Person Is : " & Age)
        Console.WriteLine("The Country It Belongs To Is : " & CountryName)

    End Sub

End Class

Sub Main()

     ' Way First To Declare Object
        Dim ob As New MyFirstClass()
        ob.Display()

     ' Way Second To Declare and Initialize Object
        Dim obj As New MyFirstClass With {.Name = "Osama", _
                                          .Age = 21, _
                                          .CountryName = "Pakistan"
                                         }

        obj.Display()

     ' Way Third To Declare and Initialize Object
        Dim obj2 As New MyFirstClass("Bilal", 23, "Saudia Arabia")
        obj2.Display()


     ' Way Fourth To Declare and Initialize Object
        Dim obj3 As New MyFirstClass()
        obj3.Name = "Saad"
        obj3.Age = 21
        obj3.CountryName = "Pakistan"

        obj3.Display()

End Sub

see this in c#.net

0 comments: