YouTip LogoYouTip

Csharp Struct

In C#, a struct (structure) is a value type used to organize and store related data. In C#, a struct is a value-type data structure, which allows a single variable to store various types of related data. The `struct` 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 properties for each book: * Title * Author * Subject * Book ID To define a struct, 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 `Books` struct as follows: ```csharp struct Books { public string title; public string author; public string subject; public int book_id; }; The following program demonstrates the usage of a struct: ## Example ```csharp 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 specification */ Book1.title = "C Programming"; Book1.author = "Nuha Ali"; Book1.subject = "C Programming Tutorial"; Book1.book_id = 6495407; /* book 2 specification */ Book2.title = "Telecom Billing"; Book2.author = "Zara Ali"; Book2.subject = "Telecom Billing Tutorial"; Book2.book_id = 6495700; /* print Book1 info */ 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 info */ 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 Structs provide a lightweight data type suitable for representing simple data structures, offering good performance characteristics and value semantics: * Structs can have methods, fields, indexers, properties, operator methods, and events, making them suitable for representing lightweight data such as coordinates, ranges, dates, and times. * Structs can define constructors but cannot define destructors. However, you cannot define a parameterless constructor for a struct. The parameterless (default) constructor is automatically defined and cannot be changed. * Unlike classes, structs cannot inherit from other structs or classes. * Structs cannot be used as the base struct for other structs or classes. * Structs can implement one or more interfaces. * Struct members cannot be specified as `abstract`, `virtual`, or `protected`. * When you create a struct object using the `New` operator, an 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, fields are only assigned values after all fields are initialized, and the object can then be used. * Struct variables are typically allocated on the stack, which makes their creation and destruction faster. However, if a struct is used as a field in a class that is a reference type, the struct will be stored on the heap. * Structs are mutable by default, meaning you can modify their fields. However, if a struct is defined as `readonly`, its fields become immutable. Classes and structs have different considerations in design and usage. 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 management overhead of references. Classes and structs have several fundamental differences: **Value Type vs Reference Type:** * **Structs are Value Types:** Structs are value types, and they are allocated memory on the stack, not on the heap. When a struct instance is passed to a method or assigned to another variable, the entire content of the struct is copied. * **Classes are Reference Types:** Classes are reference types, and they are allocated memory on the heap. When a class instance is passed to a method or assigned to another variable, a reference (memory address) is passed, not a copy of the entire object. **Inheritance and Polymorphism:** * **Structs Cannot Inherit:** Structs cannot inherit from other structs or classes, nor can they be used as base structs for other structs or classes. * **Classes Support Inheritance:** Classes support inheritance and polymorphism, allowing new classes to be derived to extend the functionality of existing classes. **Default Constructor:** * **Structs Cannot Have a Parameterless Constructor:** Structs cannot contain a parameterless constructor. * **Classes Can Have a Parameterless Constructor:** Classes can contain a parameterless constructor. If no constructor is provided, the system provides a default parameterless constructor. **Assignment Behavior:** * Variables of class type store a reference upon assignment, so two variables point to the same object. * Struct variables copy the entire struct upon assignment, so each variable has its own independent copy. **Passing Mechanism:** * Objects of class type are passed by reference in method calls, meaning changes made to the object within the method will affect the original object. * Struct objects are typically passed by value, meaning a copy of the struct is passed, not the original struct object itself. Therefore, changes made to the struct within a method do not affect the original object. **Nullability:** * **Structs are value types and cannot be directly set to `null`:** Because `null` is the default value for reference types, not value types. If you need to represent a missing or invalid state for a struct variable, you can use `Nullable` or the shorthand `T?`. * **Classes are nullable by default:** Instances of a class can be `null` by default because they are reference types. **Performance and Memory Allocation:** * **Structs are generally more lightweight:** Since structs are value types and allocated on the stack, they are generally more lightweight than classes, 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 sections demonstrate that structs cannot contain a parameterless constructor, cannot inherit, and that copying a struct instance copies the entire content. Conversely, classes can contain a parameterless constructor, can inherit, and copying an instance copies the reference. ## Example ```csharp using System; // Struct declaration struct MyStruct { public int X; public int Y; // Struct cannot have a parameterless constructor // public MyStruct() // { // } // Parameterized constructor public MyStruct(int x, int y) { X = x; Y = y; } // Struct cannot inherit // struct MyDerivedStruct : MyBaseStruct // { // } } // Class declaration class MyClass { public int X; public int Y; // Class can have a parameterless constructor public MyClass() { } // Parameterized constructor public MyClass(int x, int y) { X = x; Y = y; } // Class supports inheritance // class MyDerivedClass : MyBaseClass // { // } } class Program { static void Main() { // Struct is a value type, allocated on the stack MyStruct structInstance1 = new MyStruct(1, 2); MyStruct structInstance2 = structInstance1; // Copies the entire struct // Class is a reference type, allocated on the heap MyClass classInstance1 = new MyClass(3, 4); MyClass classInstance2 = classInstance1; // Copies 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 affects other instances classInstance1.X = 6; Console.WriteLine($"Class: {classInstance1.X}, {classInstance2.X}"); } } Based on the above discussion, let's rewrite the previous example: ## Example ```csharp 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 specification */ Book1.setValues("C Programming", "Nuha Ali", "C Programming Tutorial", 6495407); /* book 2 specification */ Book2.setValues("Telecom Billing", "Zara Ali", "Telecom Billing Tutorial", 6495700); /* print Book1 info */ Book1.display(); /* print Book2 info */ 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 : 6495700
← Csharp EnumCsharp String β†’