top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

    Get Free Article Updates

Facebook Login
Site Registration

Understanding Access Modifiers In VB.NET

0 votes
145 views

Introduction

Access modifiers decide accessibility of your class or class member. There are five accessibility levels in VB.NET. They are:

  • Private
  • Protected
  • Friend (internal in C#)
  • Protected friend (protected internal in C#)
  • Public

This article examines all them with examples. Even though the examples are in VB.NET, they can be easily ported to C# as most of the keywords are same.

Public Access

Many programmers have habit of making everything public in their applications. This is fine for test applications but when you are developing real life applications you should expose only the data or functionality that is necessary by the user of your class. Classes and class members marked with Public access modifier are available in the same class, all the classes from the same project and to all other projects as well. This access specifier is least restrictive. Following is an example of public access specifier.

Public Class Book
   Public Title As String
End Class

Public Class BookUser
   Public Sub SomeMethod()
	Dim x as new Book()
	x.Title="VB.NET Programming"
  End Sub
End Class

Restricting access to classes and class members is not only a good programming practice but is also necessary to avoid any accidental misuse of your classes. Let us now discuss each of the remaining access modifiers in detail

Private Access

Private access modifier is applicable only to the members of a type. It restricts access to the members within the type itself. Consider following class:

    Public Class Book
        Private strTitle As String

        Public Property Title()
            Get
                Return strTitle
            End Get
            Set(ByVal Value)
                strTitle = Value
            End Set
        End Property
    End Class

Here, the member variable strTitle is declared as private inside a class Book. Hence, it cannot be accessed from outside the class Book. Remember that private access modifier is applicable only to type members not to the type itself. This means you cannot declare a class as private but if your class is a nested then it can be declared as private. For example following declaration is invalid:

Namespace n1

    Private Class Book

    End Class

End Namespace

However, following declaration of nested class is valid:

Namespace n1
    Public Class Book
        Private Class NestedBook
        End Class
    End Class
End Namespace

Protected Access

Private access modifier allows us to hide members from others but what if some one is inheriting from your class? In many cases you want that members of base class should be available in derived class. This cannot be achieved with private modifier. Protected access specifier provide such access. The members marked with protected access modifier can be accessed in the same class and all the classes inherited from it but they are not available to other classes. Following is an example of using protected access specifier:

    Public Class Class1
        Protected age As Integer

        '... other code
    End Class

    Public Class Class2
        Inherits Class1

        Public Sub SomeMethod()
            age = 99 'OK
        End Sub
    End Class

    Public Class Class3
        Public Sub SomeMethod()
            Dim x As New Class1()
            x.age = 99 'ERROR
        End Sub
    End Class

Friend Access

Now going one step further let us assume that you want that all the classes from your project should be able to access to your class members but classes external to your project should not be able to do so. In this case neither private nor protected can help. Only your �Friend� can help you out. You guessed it! The friend access modifier is used to declare your class members such that any class from the same project will be able to access them but external classes cannot. Note that this access modifier is applicable to class definitions also. Following are the examples of using Friend members and classes.

Assembly1.dll

   Public Class Class1
        Friend age As Integer
        '... other code
   End Class

    Public Class Class2
        Public Sub SomeMethod()
            Dim x As New Class1()
            x.age = 99 'OK
        End Sub
    End Class

Assembly2.dll

    Public Class Class3
        Public Sub SomeOtherMethod()
            Dim x As New Class1()
            x.age = 99 'ERROR
        End Sub
    End Class

When applied to class the class will be available only in the project in which it is declared.

Assembly1.dll

    Friend Class Class3
        Public Sub SomeMethod()

        End Sub
    End Class

    Public Class Class4
        Public Sub SomeOtherMethod()
            Dim x As Class3 'OK
        End Sub
    End Class

Assembly2.dll

    Dim x As TestComp1.n1.Class3 'ERROR

Note: In C# internal keyword serves the same purpose as Friend keyword in VB.NET.

Protected Friend Access

Protected Friend access modifier is a combination of protected and friend access modifiers and allows access to class members in the same project and all the inherited types.

Summary

This article examined various access modifiers available in .NET. Restricting access to your class members is not only a good practice but also make your classes less error prone and robust. They will also avoid any accidental misuse of class members.

posted Nov 29, 2016 by Shivaranjini

  Promote This Article
Facebook Share Button Twitter Share Button LinkedIn Share Button


Related Articles

Introduction

Visual Basic as a language never had provision of pointers or raw memory management as in C or C++. However, in VB.NET you can do so using certain .NET framework structures and classes. They include IntPtr, Marshal and GCHandle. These structures and classes allow you to communicate with managed and unmanaged environments. In this article I (Bipin Joshi) will show you how to use these structures and classes to perform pointer and unmanaged memory operations. Though the examples I give are in VB.NET, converting them to C# should not be a problem. Also note that, for the sake of simplicity I have not included any unmanaged code samples here. My aim is to illustrate use of these structures and classes so that one can use them as per individual requirements.

About IntPtr structure

IntPtr is a structure that acts as an integer pointer that is designed to be platform specific. This structure can be used in languages that do or do not support pointers. .NET file IO classes use this structure extensively for holding file handles.

About Marshal class

The IntPtr structure simply acts as a pointer to platform specific integer. It does not have any ability to write or read data at that memory location. You need to use Marshal class residing in System.Runtime.InteropServices namespace. This class provides collection of methods for allocating unmanaged memory, copying unmanaged memory blocks, and converting managed to unmanaged types. Make sure you import System.Runtime.InteropServices in your code.

About GCHandle structure

The GCHandle structure provides a means for accessing a managed object from unmanaged memory. This can be used to control garbage collection of your object when unmanaged code is using it.

Writing and reading an integer value

In our first example, we will store an integer value in memory using Marshal class. Then we will get pointer to its memory location and store it in IntPtr structure. Finally, we will read value back using Marshal class again.

Dim ptr As IntPtr
Dim n as Integer=123
ptr = Marshal.AllocHGlobal(4)
Marshal.WriteInt32(ptr, n)

Here, we declared a variable of type IntPtr. We then used AllocHGlobal shared method of Marshal class that allocates a memory from global heap of 4 bytes and returns its address. We collect the address in our IntPtr variable. We then called the WriteInt32 method of Marshal class and passed memory address for writing operation followed by integer to be written.

You can read value from a memory location as follows:

Dim myint as Integer=Marshal.ReadInt32(ptr)

Writing and reading strings

In this example we will write a managed string to heap and then read it back.

Dim str as String = "hello world"
Dim ptr As IntPtr = Marshal.StringToHGlobalAuto(str)
Dim mystring As String = Marshal.PtrToStringAuto(ptr)

Here, we used StringToHGlobalAuto() method of marshal class that copies the contents of a managed string into unmanaged memory. We collect the memory address in IntPtr structure. To read the string back we used PtrToStringAuto() method of Marshal class that returns a string at specified memory location.

Writing and reading structures

In the next example we will see how to write and read structures using Marshal class and IntPtr structure.

Public Structure Point
   Dim x As Integer
   Dim y As Integer
End Structure

Dim mystruct1,mystruct2 As Point
mystructure.x=100
mystructure.y=200
Dim ptr As IntPtr = Marshal.AllocHGlobal(Marshal.SizeOf(mystruct))
Marshal.StructureToPtr(mystruct, ptr, True)
mystruct2 = Marshal.PtrToStructure(ptr, New Point().GetType)

Here, we will be using a structure called Point. This code is similar to example 1 but note how we used SizeOf method of Marshal that returns size of our structure variable. The StructureToPtr method accepts the structure variable to be written, the IntPtr instance that will be returned and flag indicating whether Marshal class should call DestroyStructure method. It is recommended that you set this flag to True as setting it to false can cause memory leaks. Finally, we used PtrToStructure method of Marshal class to read the structure back.

Writing and reading objects

Up till now we saw how to read and write value types using Marshal and IntPtr class. The managed objects work a bit differently. You need to use GCHandle to read and write these objects. Following code shows how:

Public Class Employee
    Public Name As String
    Public Salary As Decimal
End Class

Dim gh As GCHandle
Dim emp As New Employee
emp.Name = "John"
emp.Salary = 12345.67
gh = GCHandle.Alloc(emp)
Dim emp2 As Employee = gh.Target
gh.Free()

Here, we used GCHandle (Garbage Collector Handle) class to allocate and de allocate memory to our instance of employee class. The shared (static) Alloc method accepts the object to store in the memory and returns an instance of GCHandle class. We can point to the reference of our object via Target property of this object. Once we are done with the object we can release memory consumed by it using Free method of GCHandle instance.

Summary

Pointer like operations and unmanaged operations were never easy in VB.NET. However, IntPtr and GCHandle structures and Marshal class allow you to achieve similar effect.

READ MORE
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...