Blue Theme Orange Theme Green Theme Red Theme
 
Discover the top 5 tips for understanding .NET Interop
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » VB.NET » Understanding Structures in VB.NET

Understanding Structures in VB.NET

A structure in VB.NET is simply a composite data type consisting of a number elements of other types. A VB.NET structure is a value type and the instances or objects of a structure are created in stack.

Author Rank :
Page Views : 184263
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

A structure in VB.NET is simply a composite data type consisting of a number elements of other types. A VB.NET structure is a value type and the instances or objects of a structure are created in stack. The structure in VB.NET can contain fields, methods, constants, constructors, properties, indexers, operators and even other structure types. 

Structure Declaration & Object Creation.

The keyword struct can be used to declare a structure. The general form of a structure declaration in VB.NET is as follows.         

<modifiers> struct <struct_name>
If (True) Then
End If 'Structure members 

Where the modifier can be private, public, internal or public. The struct is the required keyword.

For example

Structure MyStruct
Public x As Integer
Public y As Integer
End
Structure 'MyStruct

The objects of a strcut can be created by using the new operator as follows. 
 
Dim ms As New MyStruct()

The individual members of a struct can be accessed by using the dot (.) operator as showing below.

ms.x = 10
ms.y = 20

Remember that unlike classes, the strcut object can also be created without using the new operator.

Dim ms As MyStruct

But in this case all fields of the struct will remain unassigned and the object can't be used until all of the fields are initialized. 

Structs & Fields.

A struct in VB.NET can contain fields. These fields can be declared as private, public, internal. Remember that inside a struct, we can only declare a field. We can't initialize a field inside a struct. However we can use constructor to initialize the structure fields. 

The following is not a valid VB.NET struct and the code will not compile, since the fields inside the structure are trying to initialize.

Structure MyStruct
Private x As Integer = 20
Private y As Integer = 20
End Structure 'MyStruct

A valid VB.NET structure is showing below. 

Imports System
Structure MyStruct
Public x As Integer
Public y As Integer
End
Structure 'MyStruct
Class MyClient
Public Shared Sub Main()
Dim ms As New MyStruct
ms.x = 10
ms.y = 20
Dim sum As Integer = ms.x + ms.y
Console.WriteLine("The sum is {0}", sum)
End Sub 'Main
End Class 'MyClient
 

However a struct can contain static fields, which can be initialized inside the struct. The following example shows the use of static fields inside a struct. 

Imports System
Structure MyStruct
Public Shared x As Integer = 25
Public Shared y As Integer = 50
End Structure 'MyStruct
Class MyClient
Public Shared Sub Main()
Dim sum As Integer = MyStruct.x + MyStruct.y
Console.WriteLine("The sum is {0}", sum)
End Sub 'Main
End Class 'MyClient

Remember that static fields can't be accessed by an instance of a struct. We can access them only by using the struct names. 

Struct & Methods.

A VB.NET struct can also contain methods. The methods can be either static or non-static. But static methods can access only other static members and they can't invoke by using an object of the structure. They can invoke only by using the struct name.

An example is shown below.

Imports System
Structure MyStruct
Private Shared x As Integer = 25
Private Shared y As Integer = 50
Public Sub SetXY(ByVal i As Integer, ByVal j As Integer)
x = i
y = j
End Sub 'SetXY
Public Shared Sub ShowSum()
Dim sum As Integer = x + y
Console.WriteLine("The sum is {0}", sum)
End Sub 'ShowSum
End Structure 'MyStruct
Class MyClient
Public Shared Sub Main()
Dim ms As New MyStruct
ms.SetXY(100, 200)
MyStruct.ShowSum()
End Sub 'Main
End Class 'MyClient

The methods inside a struct can also be overloaded as like inside a class. For example 

Imports System
Structure MyStruct
Private Shared x As Integer = 25
Private Shared y As Integer = 50
Public Overloads Sub SetXY(ByVal i As Integer, ByVal j As Integer)
x = i
y = j
End Sub 'SetXY
Public Overloads Sub SetXY(ByVal i As Integer)
x = i
y = i
End Sub 'SetXY
End Structure 'MyStruct
Class MyClient
Public Shared Sub Main()
Dim ms1 As New MyStruct
Dim ms2 As New MyStruct
ms1.SetXY(100, 200)
ms2.SetXY(500)
End Sub 'Main
End Class 'MyClient

Structs & Constructors.

A VB.NET struct can declare constrcutor, but they must take parameters. A default constructor (constructor without any parameters) are always provided to initialize the struct fields to their default values. The parameterized constructors inside a struct can also be overloaded.          

Imports System
Structure MyStruct
Private x As Integer
Private y As Integer
If
(True) Then
x = i
y = j
End If
Public Sub New(ByVal i As Integer)
x =(y <<= i)
'ToDo: Unsupported feature: assignment within expression. "=" changed to "<="
End Sub 'New
Public Sub ShowXY()
Console.WriteLine("The field values are {0} & {1}", x, y)
End Sub 'ShowXY
Class MyClient
Public Shared Sub Main()
Dim ms1 As New MyStruct(10, 20)
Dim ms2 As New MyStruct(30)
ms1.ShowXY()
ms2.ShowXY()
End Sub 'Main
End Class 'MyClient

The 'this' operator can also be used in constructors and parameterized constructors can be chained inside a C# constructor. An example is given below. 

Imports System
Structure MyStruct
Private x As Integer
Private y As Integer
Public Sub New(ByVal i As Integer, ByVal j As Integer)
MyClass.New(i + j)
End Sub 'New
Public Sub New(ByVal i As Integer)
x =(y <<= i)
'ToDo: Unsupported feature: assignment within expression. "=" changed to "<="
End Sub 'New
Public Sub ShowXY()
Console.WriteLine("The field values are {0} & {1}", x, y)
End Sub 'ShowXY
End Structure 'MyStruct
Class MyClient
Public Shared Sub Main()
Dim ms1 As New MyStruct(10, 20)
ms1.ShowXY()
End Sub 'Main
End Class 'MyClient

Structs & Properties.

The properties can be declared inside a struct as shown below.         

'VB.NET: Property
Imports System
Class MyStruct
Private x As Integer '
Public Property X() As Integer
Get
Return x
End Get
Set(ByVal Value As Integer)
x = value
End Set
End Property
End
Class 'MyStruct
Class MyClient
Public Shared Sub Main() '
Dim ms As New MyStruct
ms.X = 10
Dim xVal As Integer = ms.X
Console.WriteLine(xVal)
'Displays 10
End Sub 'Main
End Class 'MyClient 

Structs & Indexers. 

The indexers can also be used with a VB.NET struct. An example is shown below.     

Imports System
Imports System.Collections
Structure MyStruct
Public data() As String
Default Public Property Item(ByVal index As Integer) As String
Get
Return data(index)
End Get
Set(ByVal Value As String)
data(index) = value
End Set
End Property
End
Structure 'MyStruct
Class MyClient
Public Shared Sub Main()
Dim ms As New MyStruct
ms.data =
New String(5) {}
ms(0) = "Rajesh"
ms(1) = "A3-126"
ms(2) = "Snehadara"
ms(3) = "Irla"
ms(4) = "Mumbai"
Console.WriteLine("{0},{1},{2},{3},{4}", ms(0), ms(1), ms(2), ms(3), ms(4))
End Sub 'Main
End Class 'MyClient

Structs & Operator Overloading.

The operators can be overloaded inside a VB.NET structure also. The same rules applicable with respect to a VB.NET class is also applicable here. Both unary and binary operators can be overloaded.         

Imports System
Structure Complex
Private x As Integer
Private y As Integer
Public Sub New(ByVal i As Integer, ByVal j As Integer)
x = i
y = j
End Sub 'New
Public Sub ShowXY()
Console.WriteLine("{0} {1}", x, y)
End Sub 'ShowXY
Public Shared Function UnaryMinus(ByVal c As Complex) As Complex
'References to operator will need to be replaced by calls to this method
Dim temp As New Complex
temp.x = -c.x
temp.y = -c.y
Return temp
End Function 'UnaryMinus
End Structure 'Complex
Class MyClient
Public Shared Sub Main()
Dim c1 As New Complex(10, 20)
c1.ShowXY()
' displays 10 & 20
Dim c2 As New Complex
c2.ShowXY()
' displays 0 & 0
c2 = -c1
c2.ShowXY()
' diapls -10 & -20
End Sub 'Main
End Classs 'MyClient

Structs & Inheritance.

There is no inheritance for structs as there is for classes. A struct can't inherit from another struct or class and it can't be the base class for a class. But remember that in VB.NET all types are directly or indirectly inheriting from the super base class object and hence the structure also. Since structs doesn't support inheritance, we can't use the keywords virtual, override, new, abstract etc with a struct methods. VB.NET struct types are never abstract and are always implicitly sealed. The abstract or sealed modifiers are not permitted in a struct declaration. 

Since inheritance is not supported for structs, the declared accessibility of a struct member can’t be protected or protected internal. Since all struct types are implicitly inherit from object class, it is possible to override the methods of the object class inside a struct by using the keyword override. Remember that this is special case in VB.NET structs. 

Structs & Interfaces.

Just like classes, a VB.NET struct can also implement from an interface. For example         

Imports System
Interface IInterface
Sub Method()
End Interface 'Interface
Structure Complex
Implements IInterface 'ToDo: Add Implements Clauses for implementation methods of these interface(s)
Public Sub Method()
Console.WriteLine("Struct Method")
End Sub 'Method
End Structure 'Complex
Class MyClient
Public Shared Sub Main()
Dim c1 As New Complex
c1.Method()
End Sub 'Main
End Class 'MyClient

Structs & Classes.

The structs in VB.NET seems to similar to classes. But they are two entirely different aspects of the language. The classes are reference types while a struct is a value type in VB.NET. The objects of class types are always created on heal while the objects of struct types are always created on the stack. But VB.NET structs are useful for small data structures that have value semantics. Complex numbers, points in a co-ordinate systems etc are good examples for struct types.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Rajesh VS
Rajesh V.S is a software engineer in the area of C/C++/JAVA for the last 5 years. Currently he is interested in core C# language. He is Sun Certified Java Programmer. His other area of interest includes Design Patterns and CORBA. He is also a writer of numerous articles for many technical Web sites.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
StructMap by Scot On May 3, 2007
I'm having a problem with trying to send a structure through web services. Here is what my error is.

“Unable to cast object of type 'Scot_s_Demo.searchparams' to type 'Scot_s_Demo.getaninfocard.Structmap'.”


It calls a function called Structmap that isn't anything that we have programmed. Here is my other code...

Private Sub btn_sinfocard_click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btn_sinfocard.Click
Scot_s_Demo.dcs.mainman.techval.InfocardServiceService
Dim myparams = New Scot_s_Demo.Searchparams()

myparams.InfoCard_Number = "444"
myparams.Title = "my title"
myparams.Revision = "1"
myparams.Lifecycle_Status = "my vault"
lbl_insertdocnumber.Text = myparams.InfoCard_Number
lbl_inserttitle.Text = myparams.Title
lbl_insertrev.Text = myparams.Revision
lbl_insertvault.Text = myparams.Lifecycle_Status
lbl_Connection.Text = connectionID
lbl_userName.Text = username
'myparams1 = myparams
Dim obj As Scot_s_Demo.getaninfocard.InfocardServiceService
Dim results = obj.getInfoCardList(connectionID, myparams)
lbl_userName.Text = results
End Sub

Any ideas?
Reply | Email | Modify 
DevExpress Free UI Controls
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.