Wednesday, 11 January 2012

Structures


Structures are used to create a variable set of different datatypes in VB.NET (In
earlier versions of VB we use TYPE and END TYPE to define it). Here it is
defined with STRUCTURE and END STRUCTURE keyword.
It supports allmost all the features of OOPS, like
• Implementing interfaces
• Constructors, methods, properties, fields, constants and events
• Shared constructors
Ex: -
Defining the structure:-
VB.NET
Structure Person
Public FirstName As String
Public LastName As String
Public Address As String
Public Pincode As String
Public DateOFBirth As DateTime
Public Sub DisplayInfo()
Dim msg As String
msg = FirstName & " " & LastName & vbCrLf
msg = msg & Address & vbCrLf
msg = msg & "PIN – " & Pincode
msg = msg & "Date of Birth : " & DateOFBirth.ToString
End Sub
End Structure
C#
struct Person
{
Public String FirstName;
Public String LastName ;
Public String Address ;
Public String Pincode ;
Public DateTime DateOFBirth;
Public void DisplayInfo()
{
String msg=new String();
msg = FirstName + " " + LastName ;
msg = msg + Address ;
msg = msg + "PIN – " + Pincode;
msg = msg + "Date of Birth : " + DateOFBirth.ToString;
}
}
In the example a Person structure is declared to hold the a person’s details like
name, address, pincode etc., we have already seen this person details in terms
of a class object. Basically the structures are used to hold the set of values like
array. Theoritically arrays holds a set of single datatype values, but structures
holds a set of different datatype values. Due to the OOPS feature of .NET we can
implement the methods and properties in the structures too. This is shown in the
person structure. Here the Firstname,Lastname,Address,Pincode,Dateofbirth are
all the variables of person structure with different datatype declarations, where
DisplayInfo is a method to disputably the information.
Variables holds the data and methods operates on the data stored in it as in the
normal class object.
Usage of the structure:-
VB.Net
'Creating an instance of the structure like a normal class variable
Dim varPerson As Person = New Person()
'Setting the structure variables with the values
varPerson.firstname = “Rama”
varPerson.lastname = “Lakan”
varPerson.address = “Mysore”
varPerson.pincode = “570002”
varPerson.dateofbirth = “25/06/1977”
'Calling the strcuture method to manipulate and display the person address
varPerson.displayinfo()
C#
Person varPerson =New Person();
'Setting the structure variables with the values
varPerson.firstname = “Rama”;
varPerson.lastname = “Lakan”;
varPerson.address = “Mysore”;
varPerson.pincode = “570002”;
varPerson.dateofbirth = “25/06/1977”;
'Calling the strcuture method to manipulate and display the person address
varPerson.displayinfo();