Accessibility

 <  Day Day Up  >  

Every declaration in a Visual Basic .NET program has a particular access level associated with it. This access level determines the accessibility of the declaration by other parts of the code, or by other assemblies that might reference the compiled assembly. Accessibility is enforced not only by the compiler but also by the .NET Framework; it is part of the general security model of the Framework. Access levels for a member are specified by modifying a declaration with the desired access level.

The two simplest access levels are Public and Private . Public members can be accessed by anyone , without restriction, while Private members can only be accessed by the type that they are declared in. For example:

 Class Employee   Public Name As String   Private Salary As Double End Class Module Test   Sub Main()     Dim c As Employee = New Employee()     ' OK, Name is public     c.Name = "John Doe"     ' Invalid, Salary is private     c.Salary = 100403.33   End Sub End Module 

This example declared a class, Employee , that has two members: a Public field, Name , and a Private field, Salary . The Main subroutine can change the Name field because its Public access means anyone can access it. Main cannot change the Salary field, however, because that field is Private to the class.

The Friend access level allows access from within an assembly, but not outside of it. It is useful when writing objects that will go into a class library that will be used by other assemblies. Friend members can be used freely within the class library, but other assemblies will have no access to the members.

It is worth noting that accessibility applies to a declaration, not a particular instance of a type. So two Employee objects could access each other's Salary field.

 Class Employee   Public Name As String   Private Salary As Double   Public Sub CompareSalaries(ByVal Other As Employee)     Console.Write(Name & " makes ")     If Salary > Other.Salary Then       Console.Write("more than ")     Else If Salary < Other.Salary Then       Console.Write("less than ")     Else       Console.Write("the same as ")     End If     Console.WriteLine(Other.Name)   End Sub End Class 

One important thing to remember is that the access of any declaration may be constrained by the access of a declaration that contains it. For example, it is reasonable and valid to declare a Public field in a class that is declared to be Friend . Even though the field is Public , any access to the field has to come through the class, so the field's effective access level is Friend . The general rule of thumb is this: A member's access can never be greater than that of all its containers.

 <  Day Day Up  >  


The Visual Basic .NET Programming Language
The Visual Basic .NET Programming Language
ISBN: 0321169514
EAN: 2147483647
Year: 2004
Pages: 173
Authors: Paul Vick

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net