C# Struct
In C#, a struct is a value type used to organize and store related data.
In C#, a struct is a value type data structure, which enables a single variable to store related data of various data types.
structThe keyword is used to create a struct.
A struct is used to represent a record. Suppose you want to track the status of books in a library; you might want to track the following attributes of each book:
- Title
- Author
- Subject
- Book ID
Define struct
To define a struct, you must usestructstatement.
structThe statement defines a new data type with multiple members for the program.
For example, you can declare the Book struct in the following way:
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.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 details */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;
/* book 2 details */
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 above code 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
Characteristics of C# Structures
A struct provides a lightweight data type, suitable for representing simple data structures, with good performance characteristics and value semantics:
- A struct can have methods, fields, indexes, properties, operator methods, and events, and is suitable for representing lightweight data situations such as coordinates, ranges, dates, times, etc.
- A struct can define constructors, but cannot define destructors. However, you cannot define a parameterless constructor for a struct. The parameterless constructor (default) is automatically defined and cannot be changed.
- Unlike classes, structs cannot inherit from other structs or classes.
- A struct cannot be used as a base struct for other structs or classes.
- Structures can implement one or more interfaces.
- Struct members cannot be declared as abstract, virtual, or protected.
- When you useNewWhen the `new` operator is used to create a struct object, the appropriate constructor is called to create the struct. Unlike classes, structs can be instantiated without using the `new` operator.
- If the New operator is not used, only after all fields have been initialized will the fields be assigned and the object be usable.
- Struct variables are usually allocated on the stack, which makes their creation and destruction faster. However, if a struct is used as a field of a class, and the class is a reference type, the struct will be stored on the heap.
- Structs are mutable by default, which means you can modify their fields. However, if a struct is defined as readonly, its fields will be immutable.
Class vs Structure
Classes and structs have different considerations in design and use. Classes are suitable for representing complex objects and behaviors, supporting inheritance and polymorphism, while structs are more suitable for representing lightweight data and value types, to improve performance and avoid the overhead of reference management.
Classes and structs have the following basic differences:
Value types vs reference types:
- A struct is a value type (Value Type):Structures are value types. They allocate memory on the stack rather than on the heap. When a struct instance is passed to a method or assigned to another variable, the entire contents of the struct are copied.
- A class is a reference type (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 the reference (memory address), not a copy of the entire object.
Inheritance and polymorphism:
- Structures cannot inherit:A struct cannot inherit from other structs or classes, nor can it serve as a base class for other structs or classes.
- Classes support inheritance:Classes support inheritance and polymorphism, and can extend the functionality of existing classes by deriving new classes.
Default constructor:
- Structures cannot have parameterless constructors:A struct cannot contain a parameterless constructor.
- Classes can have parameterless constructors:A class can contain a parameterless constructor. If no constructor is provided, the system provides a default parameterless constructor.
Assignment behavior:
- When a variable of a class type is assigned, it stores a reference, so two variables point to the same object.
- When a struct variable is assigned, the entire struct is copied, so each variable has its own independent copy.
Passing method:
- Objects of class type are passed by reference during method calls, meaning that changes made to the object inside a method affect the original object.
- Struct objects are usually passed by value, meaning that a copy of the struct is passed, not the original struct object itself. Therefore, changes made to the struct inside a method do not affect the original object.
Nullability:
- A struct is a value type and cannot be directly set tonull:becausenullIt is the default value of a reference type, not the default value of a value type. If you need to represent the missing or invalid state of a struct variable, you can useNullable<T>or calledT?Nullable types.
- Classes can be null by default:Class instances can by default be
null, because they are reference types.
Performance and memory allocation:
- Structures are usually more lightweight:Since structs 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:Since classes are reference types, they may involve more memory overhead and management.
In the following example, MyStruct is a struct, while MyClass is a class.
The commented section demonstrates that structures cannot contain parameterless constructors, cannot inherit, and that copying a struct instance copies the entire contents of the struct. In contrast, classes can contain parameterless constructors, can inherit, and instance copying copies the reference.
Example
// Struct declaration
struct MyStruct
{
public int X;
public int Y;
// Structs cannot have parameterless constructors
// public MyStruct()
// {
// }
// Parameterized constructor
public MyStruct(int x, int y)
{
X = x;
Y = y;
}
// 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()
{
}
// Parameterized constructor
public MyClass(int x, int y)
{
X = x;
Y = y;
}
// Classes support inheritance
// class MyDerivedClass : MyBaseClass
// {
// }
}
class Program
{
static void Main()
{
// Structs are value types, allocated on the stack
MyStruct structInstance1 = new MyStruct(1, 2);
MyStruct structInstance2 = structInstance1; // Copy the entire structure
// Classes are reference types, allocated on the heap
MyClass classInstance1 = new MyClass(3, 4);
MyClass classInstance2 = classInstance1; // Copy the reference, pointing to the same object
// Modifying a struct instance does not affect other instances
structInstance1.X = 5;
Console.WriteLine($"Struct: {structInstance1.X}, {structInstance2.X}");
// Modifying a class instance will affect other instances
classInstance1.X = 6;
Console.WriteLine($"Class: {classInstance1.X}, {classInstance2.X}");
}
}
Based on the above discussion, let us rewrite the previous example:
Example
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 details */
Book1.setValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);
/* book 2 details */
Book2.setValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
/* Print Book1 information */
Book1.display();
/* Print Book2 information */
Book2.display();
Console.ReadKey();
}
}
When the above code 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 : 6495700other extensions