C# struct
In C#, a struct (short for structure) is a value type that encapsulates data and behavior related to a single concept. Structs are used to represent lightweight objects that typically contain a small number of fields. In this article, we'll explore what structs are, how they differ from classes, and their advantages, and provide examples to illustrate their usage.
Definition and Syntax
A struct in C# is defined using the struct keyword followed by the name of the struct. Here's the basic syntax of a struct:
public struct MyStruct
{
// Fields, properties, constructors, and methods
}
Key Characteristics of Structs
-
Value Type: Structs are value types, meaning that when you create a variable of a struct type, the variable directly contains the data, not a reference to it. This contrasts with classes, which are reference types.
-
Stack Allocation: Structs are typically allocated on the stack, which is faster than heap allocation used for reference types like classes.
-
Immutable by Default: Structs are usually immutable by default. Once a struct instance is created, its properties cannot be changed. However, you can define mutable structs if needed.
-
Value Semantics: Structs exhibit value semantics, meaning that when you assign a struct variable to another variable or pass it as a parameter to a method, a copy of the struct is made. This is in contrast to reference types, where assigning one variable to another simply copies the reference, not the underlying object.
-
No Inheritance: Structs cannot inherit from other structs or classes. They can, however, implement interfaces.
Advantages of Using Structs
-
Performance: Because structs are allocated on the stack and copied by value, they are often more efficient in terms of memory usage and performance compared to classes, especially for small, lightweight objects.
-
Semantic Clarity: Structs are well-suited for representing simple data structures and concepts where the emphasis is on the value itself rather than identity or reference semantics. They provide a clear and concise way to represent such data.
-
Thread Safety: Immutable structs are inherently thread-safe since their state cannot be modified after creation. This can simplify concurrency management in multithreaded applications.
-
Copy Semantics: Structs support copy semantics, making it easy to create and manipulate independent copies of data without worrying about unintended side effects.
Example. Employee Struct
In a small business scenario, you might have a need to manage employee data. Each employee has attributes such as name, ID, department, and salary. A struct can be used to encapsulate this data.
using System;
public struct Employee
{
public int EmployeeID { get; }
public string Name { get; }
public string Department { get; }
public decimal Salary { get; }
public Employee(int id, string name, string department, decimal salary)
{
EmployeeID = id;
Name = name;
Department = department;
Salary = salary;
}
// Override ToString method to provide a string representation of the employee
public override string ToString()
{
return $"ID: {EmployeeID}, Name: {Name}, Department: {Department}, Salary: {Salary:C}";
}
}
class Program
{
static void Main(string[] args)
{
// Create employees
Employee emp1 = new Employee(1001, "John Doe", "Sales", 50000);
Employee emp2 = new Employee(1002, "Jane Smith", "Marketing", 60000);
// Display employee information
Console.WriteLine("Employee Information:");
Console.WriteLine(emp1);
Console.WriteLine(emp2);
//o/p
//Employee Information:
//ID: 1001, Name: John Doe, Department: Sales, Salary: 50,000
//ID: 1002, Name: Jane Smith, Department: Marketing, Salary: 60,000
}
}
In this example
- We define an Employee struct with properties for EmployeeID, Name, Department, and Salary.
- We provide a constructor to initialize these properties when creating a new Employee object.
- We override the ToString() method to provide a string representation of the employee data.
- In the Main method, we create two Employee objects (emp1 and emp2) with different data.
- We then display the information of both employees using the Console.WriteLine().
Conclusion
Structs in C# provide a lightweight and efficient way to represent simple data structures and concepts. They offer performance benefits, semantic clarity, and thread safety, making them suitable for various scenarios in application development. Understanding when and how to use structs can lead to more efficient and maintainable code, especially in situations where small, immutable objects are preferred.