Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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:
Total page views :  142045
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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.


Login to add your contents and source code to 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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
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 | Delete | Modify | 
ANTS Performance Profiler 6.0
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.