What Does Instance Field Mean?
An instance field, in C#, is a variable of any type contained within a class or struct, and is used to store object data. It is a member of its containing type with one copy of the field for each instance of the containing type.
Instance fields represent the data of a class that enables an object to maintain its state. These fields are usually exposed as a property by which the internal implementation of the field can be changed as per the enhancements in the design of the class without introducing any breaking changes. This advantage negates the effect of the slight overhead in accessing the fields through properties.
The main intent of designing instance fields is to encapsulate data that must be accessed by all the methods of the class and allow the data to be stored throughout the lifetime of the instance of the class. In addition, data can be prevented from accidental corruption by hiding it with the required level of accessibility.
Instance field is also referred to as an instance variable.
Techopedia Explains Instance Field
An instance field is declared within the class block along with details of its name, access level and the data type. Its access level can be specified using any of the access modifiers, which are private, protected, public, internal and protected internal. In general, fields are used with private or protected accessibility to prevent their direct access to client code.
During the instantiation of a class, each instance of the class occupies a separate memory space, and its fields have separate and independent values. Unlike static field, which belongs to a class and is shared among all the instances of the class, instance field can be accessed only from an instance of a class.
For example, consider a class that has date as an instance field. When two instances of this class are created as X and Y, date value for object X can be changed without affecting the value of object Y.
Instance fields can be initialized using the assignment operator with an initial value when it is declared. Instance fields can also be used with a read-only modifier so that its value can be assigned only once, either in the declaration or in the constructor of its class.