Instance fields store information unique to each object. They help keep track of an object's state over time.
0
0
Instance fields and state in C Sharp (C#)
Introduction
When you want each object to remember its own data, like a person's name or age.
When you need to track changes in an object, such as a bank account balance.
When you want to keep information inside an object that other objects don't share.
When you want to model real-world things that have their own properties.
When you want to update or read data that belongs to a specific object.
Syntax
C Sharp (C#)
class ClassName { private int fieldName; // instance field public ClassName(int initialValue) { fieldName = initialValue; } }
Instance fields are declared inside a class but outside any method.
Each object (instance) of the class has its own copy of these fields.
Examples
This example shows a
color field that stores each car's color.C Sharp (C#)
class Car { private string color; // instance field public Car(string carColor) { color = carColor; } }
This example uses an instance field
count to keep track of a counter's state.C Sharp (C#)
class Counter { private int count = 0; // instance field with default value public void Increment() { count++; } public int GetCount() { return count; } }
Sample Program
This program creates a LightBulb object that remembers if it is on or off using an instance field. It shows how the state changes when switching on and off.
C Sharp (C#)
using System; class LightBulb { private bool isOn; // instance field to store state public LightBulb() { isOn = false; // starts off } public void SwitchOn() { isOn = true; } public void SwitchOff() { isOn = false; } public void ShowState() { Console.WriteLine(isOn ? "The light bulb is ON." : "The light bulb is OFF."); } } class Program { static void Main() { LightBulb bulb = new LightBulb(); bulb.ShowState(); bulb.SwitchOn(); bulb.ShowState(); bulb.SwitchOff(); bulb.ShowState(); } }
OutputSuccess
Important Notes
Instance fields keep data for each object separately, so changing one object's field does not affect others.
Use private to hide fields and protect data inside the object.
Access and change instance fields through methods or properties to control how data is used.
Summary
Instance fields store data unique to each object.
They help objects remember their own state over time.
Use methods to safely read or change instance fields.