Methods that operate on state help objects remember and change their own information. This makes programs organized and easier to understand.
0
0
Methods that operate on state in C Sharp (C#)
Introduction
When you want an object to keep track of its own data, like a bank account remembering its balance.
When you need to change the data inside an object safely, like updating a player's score in a game.
When you want to group related actions and data together, like a light switch turning on or off.
When you want to avoid repeating code by letting methods handle changes inside the object.
Syntax
C Sharp (C#)
class ClassName { private DataType stateVariable; public void MethodName(DataType parameter) { // Change or use stateVariable here } }
Methods that operate on state usually change or use variables inside the object (called fields).
These methods can be called on an object to make it do something or update its data.
Examples
This example shows a counter that remembers a number and can increase it by one.
C Sharp (C#)
class Counter { private int count = 0; public void Increment() { count = count + 1; } public int GetCount() { return count; } }
This example shows a light that can switch on or off by changing its state.
C Sharp (C#)
class Light { private bool isOn = false; public void Switch() { isOn = !isOn; // Change true to false or false to true } public bool IsLightOn() { return isOn; } }
Sample Program
This program creates a bank account that can deposit and withdraw money. It shows how methods change the account's balance safely.
C Sharp (C#)
using System; class BankAccount { private decimal balance = 0m; public void Deposit(decimal amount) { if (amount > 0) { balance += amount; Console.WriteLine($"Deposited: {amount:C}"); } else { Console.WriteLine("Deposit amount must be positive."); } } public void Withdraw(decimal amount) { if (amount > 0 && amount <= balance) { balance -= amount; Console.WriteLine($"Withdrew: {amount:C}"); } else { Console.WriteLine("Invalid withdraw amount."); } } public void ShowBalance() { Console.WriteLine($"Current balance: {balance:C}"); } } class Program { static void Main() { BankAccount account = new BankAccount(); account.Deposit(100m); account.Withdraw(30m); account.ShowBalance(); } }
OutputSuccess
Important Notes
Always keep state variables private to protect data from outside changes.
Use methods to control how state changes, adding checks to avoid mistakes.
Methods that operate on state help keep your code organized and easier to fix or improve.
Summary
Methods that operate on state let objects keep and change their own data.
Use these methods to safely update or read the object's information.
This approach makes your program clearer and easier to manage.