In C# programming, a struct (also called a structure) functions similarly to a class by holding data within a unified entity. Structs are categorized as value types, indicating they are stack-stored and passed by value rather than by reference. They encompass various data types and are defined by the user. A struct can comprise nested types, constants, fields, methods, properties, indexers, operators, events, as well as a parameterized or static constructor. The declaration of a struct is initiated with the struct keyword.
The <style> element is styled using CSS properties for a visually appealing design. The placeholder is structured with a gradient background, rounded borders, padding for spacing, and centered text alignment. Within the placeholder, there is an icon with a size of 3rem and text with a color of #9ca3af and font size of 1rem. This creates a well-defined and aesthetically pleasing layout for the placeholder.
Define a struct in C#
In C#, the format can be specified using the struct keyword.
For Example:
struct master
{
public int id;
}
Declare a struct Variable in C#
In C# development, it is necessary to define a struct variable prior to its usage. This is achieved by indicating the name of the struct followed by the name of the variable.
For Example:
struct master {
public int id;
}
. . .
// declare mst of the struct Employee
master mst;
Access the Struct Member in C#
The dot (.) operator is employed for accessing the member of a struct. Here are some instances provided below.
For Example:
struct Master {
public int id;
}
...
// declare mst of struct Master
Master mst;
// accessing the member
mst.id = 1;
Here, we utilize the mst variable along with the dot (.) operator to retrieve the properties of the master object.
Struct Example in C#
Let us take an example to define a struct in C#.
Example
using System;
struct Person
{
public string Name;
public int Age;
// Method inside struct
public void DisplayInfo()
{
Console.WriteLine("The name is " + Name );
Console.WriteLine("The age is " + Age );
}
}
class Program
{
static void Main()
{
// Declare and initialize struct variable
Person p1;
p1.Name = "Michael";
p1.Age = 25;
// Calling method
p1.DisplayInfo();
}
}
Output:
The name is Michael
The age is 25
Explanation:
In this instance, we define a structure called Individual that includes two attributes: name (string) and age (integer). Following this, a constructor with parameters is established to set the values for these attributes, along with a method named ShowDetails to output the information. Within the primary function, an instance (p1) is instantiated and the ShowDetails method is invoked to exhibit the information.
struct Constructor in C#
In C#, a constructor can be defined for a struct by using the public keyword followed by the name of the struct.
Syntax:
It has the following syntax.
struct StructName
{
// Fields
public int x;
public int y;
// Parameterized constructor
public StructName( int a, int b )
{
x = a;
y = b;
}
}
Constructor in C# struct Example
Let's consider an example to demonstrate the struct with the use of a Constructor.
Example
using System;
struct Details
{
public string name;
public int age;
// Constructor
public Details( string na_me, int a_ge )
{
name = na_me;
age = a_ge;
}
public void DisplayInfo()
{
Console.WriteLine("The name is: " + name + ", age: " + age );
}
}
class Program
{
static void Main()
{
// structure object
Details d1 = new Details("Jhonson", 25);
d1.DisplayInfo();
}
}
Output:
The name is: Jhonson, Age: 25
Explanation:
In this instance, we define a structure called Individual which holds two attributes: name (string) and age (integer). Subsequently, a constructor with parameters is established to set the values for these attributes, along with a method named ShowData to exhibit the information. Within the primary function, an instance (p1) is generated and the ShowData method is invoked to exhibit the information.
Immutable Structure (struct)
In C# programming, a structure is considered immutable when its state remains unchanged after initialization. This implies that no fields or properties within the struct can be altered post-construction.
Example of Immutable Structure
Let's consider an example to demonstrate the unchangeable nature of structures in C#.
Example
using System;
struct Details {
public readonly string name;
public readonly string contact;
public readonly string id;
public Details( string name, string contact, string id ) {
this.name = name;
this.contact = contact;
this.id = id;
}
public void ShowDetail() {
Console.WriteLine($"Name: {name}, Contact: {contact}, ID: {id} ");
}
}
class Program {
static void Main() {
Details d = new Details("Albert", "878283XXXX", "EMPO01");
d.ShowDetail();
}
}
Output:
Name: Albert, Contact: 878283XXXX, ID: EMPO01
Explanation:
In this illustration, we declare the unchangeable struct named Information which encompasses three constant fields: title, communication, and identifier. Following this, we establish a constructor with parameters and assign the values accordingly. The DisplayInformation function exhibits these values. Within the primary function, instantiate the object and invoke the DisplayInformation function to exhibit the particulars.
Array of Structures in C#
In C#, utilizing an array of structures enables the storage of numerous instances of a structure within a unified array. Accessing the structure's elements is achieved by referencing the array using a designated index.
Syntax:
It has the following syntax:
Array[ index ].Structure( data );
In this format, an index is specified to indicate the specific positions within an array where values are either added or removed, while the data represents the actual values stored within the structure.
Array of Structure Example in C#
Let's consider an example to demonstrate the array of structure in C#.
Example
using System;
public struct Emp
{
// Declare variables
public int Roll_No;
public string Name;
public int Age;
// Set the employee details
public void Set_Emp(int RollNo, string name, int age)
{
Roll_No = RollNo;
Name = name;
Age = age;
}
// Display employee details
public void Display_Emp()
{
Console.WriteLine("Employee details: ");
Console.WriteLine("Id: " + Roll_No);
Console.WriteLine("Name: " + Name);
Console.WriteLine("Age: " + Age);
Console.WriteLine("\n");
}
}
class TPT
{
static void Main(string[] args)
{
// Create an array of Emp structs
Emp[] e = {
new Emp(),
new Emp(),
new Emp()
};
// Set values for each employee
e[0].Set_Emp(1, "John", 50);
e[1].Set_Emp(2, "Thomson", 31);
e[2].Set_Emp(3, "David", 27);
// Display employee details
e[0].Display_Emp();
e[1].Display_Emp();
e[2].Display_Emp();
}
}
Output:
Employee details:
Id: 1
Name: John
Age: 50
Employee details:
Id: 2
Name: Thomson
Age: 31
Employee details:
Id: 3
Name: David
Age: 27
Explanation:
In this illustration, we specify a structure called Emp comprising three fields: RollNo, Name, and Age. Additionally, we include a pair of functions: SetEmp for setting values and DisplayEmp for presenting the employee's information. Within the primary function, a set of three Emp structures is instantiated and set up through the SetEmp function. Subsequently, the application exhibits the particulars of each employee utilizing the Display_Emp function.
Properties in C# Struct
In C# programming, the struct's properties serve to encapsulate and control access to its fields. Similar to classes, structs can feature properties equipped with get and set accessors, and they can also be designated as read-only.
Properties Struct Example in C#
Let's consider an example to demonstrate the Struct property in C#.
Example
using System;
namespace Struct {
// declare the struct
struct Stu_dent {
public int id;
// define property
public int Id {
get {
return id;
}
// sets the value
set {
id = value;
}
}
}
class Program {
static void Main(string[] args) {
// Invoke the Constructor
Stu_dent std = new Stu_dent();
std.Id = 1;
Console.WriteLine("Student Id: " + std.Id);
Console.ReadLine();
}
}
}
Output:
Student Id: 1
Explanation:
In this instance, we are working with a struct named Stu_dent, which consists of a private field called id and a public property named Id. The property Id is designed to regulate access to the id field through get and set accessors. Within the main function, a new struct instance is instantiated, a value is set to the Id property, and the outcome is showcased.
Difference between the Structure and Class
There are various distinctions between the structure and class in C#. Some key variances include:
| Structure | Class |
|---|---|
| Structure is a value type. | Class is a reference type. |
| Inheritance is not supported in the structure. | Inheritance is supported in class. |
| Structure is defined by the struct keyword. | The class is defined by the class keyword. |
| The structure members are public by default. | The class members are private by default. |
| The syntax of the structure is.Struct StructName {datatype m1;datatype m2;}; | The syntax of the class is.Class ClassName {// data member// data method}; |
Features of C# Structure:
Several features of the C# Structure are as follows.
- The structure can have methods, properties, indexers, fields, operator methods, and events.
- It can also include parameterized constructors, constants, enumerations, and nested types.
- A structure is a value type, which means that it is stored on the stack and passed by value.
- A structure can be implemented with one or more interfaces.
- Struct members cannot be protected, virtual, or abstract.
Conclusion
In summary, the C# structure (struct) stands as a fundamental concept for software developers crafting applications. It serves as a primary focus during development. A struct functions akin to a class, storing data within a unified entity. Operating as a value type, it encompasses various unique data types. Additionally, it houses multiple methods, properties, indexers, fields, operator methods, and events.
C# struct FAQs
1) What is the struct in C#?
In C#, a struct (also referred to as a structure) functions similarly to a class by serving as a container for data within a single entity. Unlike classes, structs are considered value types, leading to their storage on the stack and their passing by value rather than by reference. They can hold various data types and are classified as user-defined data types.
2) Can we define the Constructor in C#?
Yes, we can define the parameterised constructor in C#
3) Do structs support inheritance in C#?
Structs do not have the capability to participate in inheritance. They are not able to be inherited by other classes or structures.
4) How do structs and classes differ in C#?
Structs and classes differ primarily in that structs are considered value types residing on the stack, whereas classes are regarded as reference types stored in the heap.
5) Why would we use a struct instead of a class?
When a minimalistic object is required to depict a limited data set, a struct can be employed. Structs are considered more memory-efficient than classes as they are value types and stored on the stack.