Monday, April 30, 2012

Structures


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



using System;
class Test {
int classvar ;
int anothervar =20;
public Test ( )
{
classvar = 28;
}
public static void Main()
{
Test t = new Test();
ExampleStruct strct = new ExampleStruct(20);
System.Console.WriteLine(strct.i);
strct.i = 10;
System.Console.WriteLine(t.classvar);
System.Console.WriteLine(strct.i);
strct.trialMethod();
}
}
struct ExampleStruct {
public int i;
public ExampleStruct(int j)
{
i = j;

}
public void trialMethod()
{
System.Console.WriteLine("Inside Trial Method");
}
}
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.




No comments:

Using Authorization with Swagger in ASP.NET Core

 Create Solution like below LoginModel.cs using System.ComponentModel.DataAnnotations; namespace UsingAuthorizationWithSwagger.Models {     ...