C# Structure (Struct)
In C#, a struct (structure) is a value type used to organize and store related data.
In C#, a structure is a value-type data structure that allows a single variable to store related data of various types.
The struct keyword is used to create structures.
A structure is used to represent a record. Suppose you want to track the movement of books in a library; you might want to track the following properties of each book:
- Title
- Author
- Subject
- Book ID
Defining Structs
To define a structure, you must use the struct statement.
The struct statement defines a new data type with multiple members for the program.
For example, you can declare the Book structure as follows:
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
The following program demonstrates the use of structures:
Example
using
System
;
using
System.Text
;
struct
Books
{
public
string
title
;
public
string
author
;
public
string
subject
;
public
int
book_id
;
}
;
public
class
testStructure
{
public
static
void
Main
(
string
[
]
args
)
{
Books Book1
;
/* Declare Book1 of type Books */
Books Book2
;
/* Declare Book2 of type Books */
/* book 1 detail */
Book1
.
title
=
"C Programming"
;
Book1
.
author
=
"Nuha Ali"
;
Book1
.
subject
=
"C Programming Tutorial"
;
Book1
.
book_id
=
6495407
;
/* book 2 detail */
Book2
.
title
=
"Telecom Billing"
;
Book2
.
author
=
"Zara Ali"
;
Book2
.
subject
=
"Telecom Billing Tutorial"
;
Book2
.
book_id
=
6495700
;
/* print Book1 information */
Console
.
WriteLine
(
"Book 1 title : {0}"
, Book1
.
title
)
;
Console
.
WriteLine
(
"Book 1 author : {0}"
, Book1
.
author
)
;
Console
.
WriteLine
(
"Book 1 subject : {0}"
, Book1
.
subject
)
;
Console
.
WriteLine
(
"Book 1 book_id :{0}"
, Book1
.
book_id
)
;
/* print Book2 information */
Console
.
WriteLine
(
"Book 2 title : {0}"
, Book2
.
title
)
;
Console
.
WriteLine
(
"Book 2 author : {0}"
, Book2
.
author
)
;
Console
.
WriteLine
(
"Book 2 subject : {0}"
, Book2
.
subject
)
;
Console
.
WriteLine
(
"Book 2 book_id : {0}"
, Book2
.
book_id
)
;
Console
.
ReadKey
(
)
;
}
}
When the code above is compiled and executed, it produces the following result:
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
Features of C# structures
Structures provide a lightweight data type suitable for representing simple data structures, with good performance characteristics and value semantics:
- Structures can have methods, fields, indexers, properties, operator methods, and events, making them suitable for representing lightweight data such as coordinates, ranges, dates, and times.
- A structure can define constructors but cannot define destructors. However, you cannot define a parameterless constructor for a structure. A parameterless (default) constructor is defined automatically and cannot be changed.
- Unlike classes, a structure cannot inherit from another structure or class.
- A structure cannot serve as the base structure of another structure or class.
- A structure can implement one or more interfaces.
- Structure members cannot be specified as abstract, virtual, or protected.
- When you use the New operator to create a structure object, the appropriate constructor is called to create the structure. Unlike classes, a structure can be instantiated without using the New operator.
- If you do not use the New operator, fields are assigned values only after all fields have been initialized, and then the object can be used.
- Structure variables are usually allocated on the stack, which makes their creation and destruction faster. However, if a structure is used as a field of a class, and that class is a reference type, the structure will be stored on the heap.
- Structures are mutable by default, which means you can modify their fields. However, if a structure is defined as readonly, its fields will be immutable.
Class vs. structure
Classes and structures have different considerations in design and use. Classes are suitable for representing complex objects and behaviors, supporting inheritance and polymorphism, while structures are more suitable for representing lightweight data and value types, to improve performance and avoid the overhead of reference management.
Classes and structures have the following fundamental differences:
Value type vs. reference type:
- A structure is a value type: Structures are value types; they allocate memory on the stack rather than the heap. When a structure instance is passed to a method or assigned to another variable, the entire contents of the structure are copied.
- A class is a reference type: Classes are reference types; they allocate memory on the heap. When a class instance is passed to a method or assigned to another variable, what is actually passed is a reference (memory address), not a copy of the entire object.
Inheritance and polymorphism:
- Structures cannot inherit: A structure cannot inherit from another structure or class, nor can it serve as the base class of another structure or class.
- Classes support inheritance: Classes support inheritance and polymorphism; existing class functionality can be extended by deriving new classes.
Default constructor:
- Structures cannot have a parameterless constructor: A structure cannot contain a parameterless constructor.
- Classes can have a parameterless constructor: A class can contain a parameterless constructor; if no constructor is provided, the system supplies a default parameterless constructor.
Assignment behavior:
- A variable of a class type stores a reference when assigned, so two variables point to the same object.
- A structure variable copies the entire structure when assigned, so each variable has its own independent copy.
** Passing method:**
- An object of a class type is passed by reference in a method call, which means changes made to the object within the method affect the original object.
- A structure object is usually passed by value, which means a copy of the structure is passed rather than the original structure object itself. Therefore, changes made to the structure within the method do not affect the original object.
Nullability:
- **Structures are value types and cannot be directly set to null: because null is the default value for reference types, not for value types. If you need to represent a missing or invalid state for a structure variable, you can use Nullable
or a nullable type, also known as T?. - Classes can be null by default: An instance of a class can be null by default,
nullbecause they are reference types.
Performance and memory allocation:
- Structures are usually lighter: Because structures are value types and allocate memory on the stack, they are generally lighter than classes and suitable for simple data representation.
- Classes may have more overhead: Because classes are reference types, they may involve more memory overhead and management.
In the following example, MyStruct is a structure and MyClass is a class.
The comments demonstrate that a structure cannot contain a parameterless constructor, cannot inherit, and that copying a structure instance copies the entire contents of the structure. In contrast, a class can contain a parameterless constructor, can inherit, and copying an instance copies the reference.
Example
using
System
;
// structure declaration
struct
MyStruct
{
public
int
X
;
public
int
Y
;
// a structure cannot have a parameterless constructor
// public MyStruct()
// {
// }
// a parameterized constructor
public
MyStruct
(
int
x,
int
y
)
{
X
=
x
;
Y
=
y
;
}
// a structure cannot inherit
// struct MyDerivedStruct : MyBaseStruct
// {
// }
}
// class declaration
class
MyClass
{
public
int
X
;
public
int
Y
;
// a class can have a parameterless constructor
public
MyClass
(
)
{
}
// a parameterized constructor
public
MyClass
(
int
x,
int
y
)
{
X
=
x
;
Y
=
y
;
}
// a class supports inheritance
// class MyDerivedClass : MyBaseClass
// {
// }
}
class
Program
{
static
void
Main
(
)
{
// a structure is a value type, allocated on the stack
MyStruct structInstance1
=
new
MyStruct
(
1
,
2
)
;
MyStruct structInstance2
=
structInstance1
;
// copy the entire structure
// a class is a reference type, allocated on the heap
MyClass classInstance1
=
new
MyClass
(
3
,
4
)
;
MyClass classInstance2
=
classInstance1
;
// copy the reference, pointing to the same object
// modifying a structure instance does not affect other instances
structInstance1
.
X
=
5
;
Console
.
WriteLine
(
$
"Struct: {structInstance1.X}, {structInstance2.X}"
)
;
// modifying a class instance affects other instances
classInstance1
.
X
=
6
;
Console
.
WriteLine
(
$
"Class: {classInstance1.X}, {classInstance2.X}"
)
;
}
}
Let's rewrite the previous example based on the above discussion:
Example
using
System
;
using
System.Text
;
struct
Books
{
private
string
title
;
private
string
author
;
private
string
subject
;
private
int
book_id
;
public
void
setValues
(
string
t,
string
a,
string
s,
int
id
)
{
title
=
t
;
author
=
a
;
subject
=
s
;
book_id
=
id
;
}
public
void
display
(
)
{
Console
.
WriteLine
(
"Title : {0}"
, title
)
;
Console
.
WriteLine
(
"Author : {0}"
, author
)
;
Console
.
WriteLine
(
"Subject : {0}"
, subject
)
;
Console
.
WriteLine
(
"Book_id :{0}"
, book_id
)
;
}
}
;
public
class
testStructure
{
public
static
void
Main
(
string
[
]
args
)
{
Books Book1
=
new
Books
(
)
;
/* Declare Book1 of type Books */
Books Book2
=
new
Books
(
)
;
/* Declare Book2 of type Books */
/* book 1 detail */
Book1
.
setValues
(
"C Programming"
,
"Nuha Ali"
,
"C Programming Tutorial"
,
6495407
)
;
/* book 2 detail */
Book2
.
setValues
(
"Telecom Billing"
,
"Zara Ali"
,
"Telecom Billing Tutorial"
,
6495700
)
;
/* print Book1 information */
Book1
.
display
(
)
;
/* print Book2 information */
Book2
.
display
(
)
;
Console
.
ReadKey
(
)
;
}
}
When the code above is compiled and executed, it produces the following result:
Title : C Programming
Author : Nuha Ali
Subject : C Programming Tutorial
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_id : 6495700