Structure in C#
Structure:
v In
C#, Structure are used to hold data of various data types into a single
variable.
v The
struct keyword is used for
creating a structure.
v Structure
is a value type data type.
v Structures
can have methods, fields, indexers, properties, operator, methods, and events
etc.
v Structures
cannot inherit other structures or classes.
v Structures
cannot be used as a base for other structures or classes.
v A
structure can implement interfaces.
v Structure
members cannot be specified as abstract, sealed virtual, or protected.
v A
structure can be instantiated with or without using a new keyword.
v If
the New operator is not used, the fields remain unassigned and the object
cannot be used until all the fields are initialized.
Structure Declaration & Object Creation:
The keyword struct can
be used to declare a structure. The general form of a structure declaration in
C# is as follows.
AccessModifier struct StructureName
{
// Fields
// parameterized constructor
// Constants
// Properties
// Indexers
// Events
// Methods etc.
}
Where the AccessModifier can be
private, public, internal or public. The struct is the required keyword. StructureName
is user define structure name.
Example:
public struct MyStruct {
public int x;
public string y;
}
The objects of a struct can be created
by using the new operator as follows.
MyStruct ms = new MyStruct ();
Copy Structure:
In C#, user can copy one structure
object into another one using ‘=’ (Assignment) operator.
Syntax:
StructureObjectDestination = StructureObjectSources;
Nesting of Structures:
C# allows the declaration of one
structure into another structure and this concept is termed as the nesting of
the structure.
Class vs. Structure:
Class |
Structure |
1. Classes are reference types. |
Structure are value types. |
2. Objects of class types are always created on heap
memory. |
Objects of struct types are always created on the
stack. |
3. Class support inheritance. |
Structure do not support inheritance |
4. Class have default constructor. |
Structures cannot have default constructor but
contain only constructors that have parameters. |
5. Class
Implement using class
keyword. |
Structure
Implement using struct
keyword. |
6. Class always instantiated with using a new
operator. |
Structure can be instantiated with or without
using a new operator. |
Comments
Post a Comment