Link to home
Start Free TrialLog in
Avatar of jskfan
jskfanFlag for Cyprus

asked on

Public/Shared/Protected variables in VB.NET

I would like to know the difference between
Public/Shared/Protected variables in VB.NET

thanks
Avatar of Carl Tawn
Carl Tawn
Flag of United Kingdom of Great Britain and Northern Ireland image

Public means it is available to everything.
Shared means that the method/field belongs to the class rather than to an instance of the class.
Protected means it is available to the class in which it is declared and any derived classes.
SOLUTION
Avatar of kaliyugkaarjun
kaliyugkaarjun

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of jskfan

ASKER

let me see if i understand:

1 - if I declare a class / function or procedure/ variable as public, it means it's accessible through the whole projects.

2-if I  declare a function /procedure , variable as shared , it means that I can use them from another class without instanciating them.

3- if I  declare a function /procedure , variable as protected , it means that I can use them from another class but I should instanciating them.

1- Yes.
2 - Yes.
3 - No.

An example:

Public Class Base
    Protected name As String

End Class

Public Class Derived
    Inherits Base

    Public Sub New()
        Me.name = "Bob"       '// Can access name because Derived inherits from Base where name is declared protected
    End Sub
End Class

Public Class Other
    Public Sub New()
        Dim obj As New Base()
        obj.name = "Wilbur"             '// Cannot access "name" in Base because it is protected and we do not inherit from Base
    End Sub
End Class
Avatar of jskfan

ASKER

I thought when you declare a class as public , other classes can use its methods and variables without declaring them as protected.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial