What is a structure statement?

.NET framework, Structures,What is a structure statement?,Structure Declaration,Structure Methods,Structures and Class Inheritance,Vb.net structure,
Share it:



Introduction


I n the .NET framework, structures are value-based types as opposed to e.g. classes that are reference-based types. Structures are user-defined types (UDTs) that remind us of a lot of classes, with subtle but important differences to understand.



What is a structure statement?


A Vb.net structure, in the .NET framework, can be thought of as a light-weight class with the difference that structures are value-based whereas classes are reference-based types. Structures derive from System.ValueType whereas classes, ultimately, derive from System Object. Note that even the System.ValueType derives from the master base class i.e. System Object. This way, reference-based, and value-based types are bridged together and the class hierarchy is preserved in the .NET framework. Furthermore, when you initialize an instance of a structure, the initialization occurs on the stack whereas classes are always initialized on the heap (stack and heap are two different types of memory that hold application data). Structures can not inherit another class, they can only implement interfaces. Unlike structures, however, classes may inherit a class other than System. Object and may inherit interfaces. Unlike classes, however, structures can not have destructors, which are used to free resources.

Structure Declaration

Structures are usually good for modeling geometric shapes (like triangles, rectangles, etc) and other mathematical data. As an example, let's look at the System.Drawing.Point structure. As the name implies, this structure models a point in the 2D Cartesian coordinate-system that consists of an x-coordinate and a y-coordinate. One could define such a structure in terms of a class, but structures are lighter than classes, as they are quickly deallocated (removed) when they go out of defining the scope and best suit the need as we only want a sort of container to hold our data for a point.

Structure Declaration


Structures in VB.NET are declared using the Structure keyword as shown below.
Public Structure Rectangle

    Private m_width As Integer
    Private m_height As Integer

    Public Property Width() As Integer
        Get
            Return m_width
        End Get
        Set(ByVal value As Integer)
            m_width = value
        End Set
    End Property

    Public Property Height() As Integer
        Get
            Return m_height
        End Get
        Set(ByVal value As Integer)
            m_height = value
        End Set
    End Property

End Structure


The code above declares a structure called Rectangle. It has two fields m_width and m_height that together model a rectangle (of course, it does not have any information on the location of the rectangle, but this is to keep the example simple). It also defines two properties to access/alter the content of the two fields. A structure must at least have one field - empty structures are not allowed. Note that structures define an implicit default constructor that has no parameters. This default constructor initializes all the fields to their default values (Integers get a value of 0, Booleans get a value of False and so on). You can't change this behavior. You can, however, define your own custom constructors, but they each must at least have one parameter. If you define a parameterless constructor, you get a compile error. We could have defined our own custom constructor, in the above example, that would initialize the two fields as shown below
Public Structure Rectangle

    Private m_width As Integer
    Private m_height As Integer

    Public Sub New(ByVal width As Integer, ByVal height As Integer)
        m_width = width
        m_height = height
    End Sub

    Public Property Width() As Integer
        Get
            Return m_width
        End Get
        Set(ByVal value As Integer)
            m_width = value
        End Set
    End Property

    Public Property Height() As Integer
        Get
            Return m_height
        End Get
        Set(ByVal value As Integer)
            m_height = value
        End Set
    End Property

End Structure

Structure Methods

Like classes, structures may define any number of methods. Methods make structures very powerful. We will add a method to the Rectangle structure called Add that would add two structures of type Rectangle and returns the result as a new Rectangle.
Public Structure Rectangle

    Private m_width As Integer
    Private m_height As Integer

    Public Sub New(ByVal width As Integer, ByVal height As Integer)
        m_width = width
        m_height = height
    End Sub

    Public Property Width() As Integer
        Get
            Return m_width
        End Get
        Set(ByVal value As Integer)
            m_width = value
        End Set
    End Property

    Public Property Height() As Integer
        Get
            Return m_height
        End Get
        Set(ByVal value As Integer)
            m_height = value
        End Set
    End Property

    Public Function Add(ByVal rectangle As Rectangle) As Rectangle

        Dim newRect As New Rectangle

        newRect.Width = Me.Width + rectangle.Width
        newRect.Height = Me.Height + rectangle.Height

        Return newRect

    End Function

End Structure

Let's now use the Add method in the following code.


Dim rect1 As New Rectangle(5, 3)
        Dim rect2 As New Rectangle(4, 8)
        Dim rect3 As Rectangle

        rect3 = rect1.Add(rect2)

        Console.WriteLine("The width is " & rect3.Width)
        Console.WriteLine("The height is " & rect3.Height)


We begin by declaring three objects rect1, rect2 and rect3 of the Rectangle structure where the first two are initialized. Next, we add the first two rectangles using the Add method and store the resulting rectangle in rect3. The last two lines print out the result that is shown below.
The width is 9
The height is 11


Using Structures

Next, we will look at how we can use structures. Luckily, there is almost nothing new.


'Note: Despite the New keyword being used, its 
        'still allocated on the stack!
        Dim rect As New Rectangle(5, 3)

        Console.WriteLine("The width is " & rect.Width)
        Console.WriteLine("The height is " & rect.Height)
The code above initializes an object rest of the Rectangle structure using the custom constructor. Next, the width and height of the rectangle are printed out to the console window using the Width and Height properties. That's it! We could have achieved what we did above as follows. This time, we use the default constructor that initializes the two fields to 0. Then we assign our values of 5 and 3 to Width and Height respectively. Note that when you use this form of structure-initialization, you must initialize all the fields otherwise, you would end up with a compile error.
Dim rect As Rectangle

        rect.Width = 5
        rect.Height = 3

        Console.WriteLine("The width is " & rect.Width)
        Console.WriteLine("The height is " & rect.Height)

Structures and Class Inheritance

As noted earlier in Structures, structures can not inherit from another class. All structures inherit from System.ValueType by default. Structures can, however, implement as many interfaces as needed. You can read more about Inheritance and Interfaces.


Reference-based Vs. Value-based Types

As mentioned earlier, any type that inherits System.ValueType is value-based. All other types are reference-based. Value-based types are allocated on the stack whereas reference-based types are allocated on the heap. The stack is the type of memory where information about method calls (parameters, return types, etc) is stored. When an object calls a method, that method call is put on the stack. When the method finishes execution and returns to the caller (the object that called it), the information about its call is immediately removed from the stack. The objects on the heap, another type of memory, however, may still exist even though there are no active references to them. The objects will be removed when the garbage collector finally gets to it. Garbage collection in the .NET framework is an automatic mechanism for removing objects that are no longer in use and it, therefore, prevents memory leaks.



                                        Share this article with your friends
Share it:

VB.NET

Post A Comment:

0 comments: