Making a Field Static, Constant, and Read-Only
Explore how to define and use static, constant, and read-only fields in C#. This lesson helps you understand how static fields share values across instances, how constants hold unchangeable compile-time values, and how read-only fields allow immutability after initialization, enhancing your control over data behavior in classes.
We'll cover the following...
In C#, fields can be more than just data containers; they can also have attributes that dictate how their values behave. This section will explore the versatility of fields, starting with static fields that share a value among all instances. We’ll also dive into constant and read-only fields.
Making a field static
The fields we have created so far have all been instance members, meaning that a different value of each field exists for each instance of the class created. The alice and bob variables have different Name values. Sometimes, we want to define a field with only one value shared across all instances. These are called static members because fields are not the only members that can be static. Let’s see what can be achieved using static fields:
Step 1: In the PacktLibraryNetStandard2 ...