|
|
|
|
|
Home
»
VB.NET
»
Understanding Structures in VB.NET
|
|
|
Author Rank:
|
|
Total page views :
142045
|
|
Total downloads :
|
|
|
|
|
|
Similar ArticlesMost ReadTop RatedLatest
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
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.
|
|
|
|
|
|
|
|
|
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.
|
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.
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|