Struct types

Just like classes, structs in C# can be used to group together related data. Like classes, they can have constructors, fields, and methods. However, there are some differences between the implementation of structs and classes. The following are some of the key differences:

Feature Struct Class
Type Structs are managed as value type variables. This implies that the value assigned in their objects is not persisted in different scopes of the program. Classes are managed as reference type variables. This implies that the value assigned in their objects is persisted across different scopes of the program.
Constructor Unlike classes, no default constructor is managed by C#. When we go through Chapter 8, Creating and Using of Types in C#, we will explore default constructors in detail. When declaring a class, if no constructor is specified for the class, C# automatically creates a default constructor for the class.
Inheritance A struct cannot inherit from another struct. This implies that code reuse could become a challenge if we use structs. A class can inherit from other classes.
Being value type variables, when a struct object is created, the entire object – inclusive of attributes, methods, and so on – is saved in a stack. Therefore, from a performance perspective, it's essential that structs should only be used for creating lightweight objects with only a few members.

In the coming section, we will go through a code example to show how struct implementation is different from a similar implementation in classes.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.86.18