Structures

Unknown | 1:41 AM |

A structure allows you to create your own custom data types and it contains one or more
members that can be of different data types. It can contain fields, methods, Etc.,
Structures are very similar to classes but there are some restrictions present in the case of
structures that are absent in the case of classes. For example you cannot initialize
structure members. Also you cannot inherit a structure whereas classes can be inherited.
Another important feature of structures differentiating it from classes is that a structure
can't have a default parameter-less constructor or a destructor. A structure is created on
the stack and dies when you reach the closing brace in C# or the End structure in
VB.NET.
But one of the most important differences between structures and classes is that structures
are referenced by value and classes by reference. As a value type, allocated on the stack,
structs provide a significant opportunity to increase program efficiency. Objects on the
stack are faster to allocate and de-allocate. A struct is a good choice for data-bound
objects, which don’t require too much memory. The memory requirements should be
considered based on the fact that the size of memory available on the stack is limited than
the memory available on the heap.
Thus we must use classes in situations where large objects with lots of logic are required.
Struct – Code: Sample code showing the Class vs. Structures
Imports System
Class Test
Dim classvar As Integer
Dim anothervar As Integer = 20
Sub New()
classvar = 28
End Sub
Structure ExampleStruct
Dim i As Integer
Sub New(ByVal j As Integer)
i = j
End Sub
Sub trialMethod()
Console.WriteLine("Inside Trial Method")
End Sub
End Structure
Shared Sub main()
Dim t As New Test()
Dim strct As New ExampleStruct(20)
Console.WriteLine(strct.i)
strct.i = 10
Console.WriteLine(t.classvar)
Console.WriteLine(strct.i)
strct.trialMethod()
End Sub
End Class
O/P: -
28
20
10
Inside Trial Method
In the above example, I have declared and used a constructor with a single parameter for
a structure. Instead if I had tried to use a default parameter-less parameter I would have
got an error. But the same is possible in the case of classes as shown by the default
parameter-less constructor, which initializes the classvar variable to 28.
Another point to note is that a variable called anothervar has been declared and initialized
within the class whereas the same cannot be done for members of a structure.

Category:

About http://dotnetvisual.blogspot.in/:
DOT NET TO ASP.NET is a web application framework marketed by Microsoft that programmers can use to build dynamic web sites, web applications and web services. It is part of Microsoft's .NET platform and is the successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built on the Common Language Runtime, allowing programmers to write ASP.NET code using any Microsoft .NET language. create an application very easily ....