10 minlesson

Methods in Classes

Methods in Classes

Methods define the behavior of a class - the actions that objects can perform. This lesson covers instance methods, static methods, and how they interact with object data.

Instance Methods

Instance methods operate on a specific object and can access its fields and properties:

csharp
1class Dog
2{
3 public string Name { get; set; }
4 public int Age { get; set; }
5
6 // Instance method
7 public void Bark()
8 {
9 Console.WriteLine($"{Name} says: Woof!");
10 }
11
12 // Instance method using object data
13 public void DisplayInfo()
14 {
15 Console.WriteLine($"Name: {Name}, Age: {Age}");
16 }
17}
18
19Dog myDog = new Dog { Name = "Buddy", Age = 3 };
20myDog.Bark(); // Buddy says: Woof!
21myDog.DisplayInfo(); // Name: Buddy, Age: 3

Methods with Return Values

csharp
1class Rectangle
2{
3 public double Width { get; set; }
4 public double Height { get; set; }
5
6 public double GetArea()
7 {
8 return Width * Height;
9 }
10
11 public double GetPerimeter()
12 {
13 return 2 * (Width + Height);
14 }
15
16 public bool IsSquare()
17 {
18 return Width == Height;
19 }
20}
21
22Rectangle rect = new Rectangle { Width = 5, Height = 5 };
23Console.WriteLine($"Area: {rect.GetArea()}"); // 25
24Console.WriteLine($"Perimeter: {rect.GetPerimeter()}"); // 20
25Console.WriteLine($"Is square: {rect.IsSquare()}"); // True

Methods with Parameters

csharp
1class BankAccount
2{
3 public string Owner { get; set; }
4 public decimal Balance { get; private set; }
5
6 public void Deposit(decimal amount)
7 {
8 if (amount > 0)
9 {
10 Balance += amount;
11 Console.WriteLine($"Deposited {amount:C}. New balance: {Balance:C}");
12 }
13 }
14
15 public bool Withdraw(decimal amount)
16 {
17 if (amount > 0 && amount <= Balance)
18 {
19 Balance -= amount;
20 Console.WriteLine($"Withdrew {amount:C}. New balance: {Balance:C}");
21 return true;
22 }
23 Console.WriteLine("Insufficient funds or invalid amount.");
24 return false;
25 }
26
27 public void Transfer(BankAccount destination, decimal amount)
28 {
29 if (Withdraw(amount))
30 {
31 destination.Deposit(amount);
32 Console.WriteLine($"Transferred {amount:C} to {destination.Owner}");
33 }
34 }
35}
36
37BankAccount alice = new BankAccount { Owner = "Alice" };
38BankAccount bob = new BankAccount { Owner = "Bob" };
39
40alice.Deposit(1000);
41alice.Transfer(bob, 250);

Static Methods

Static methods belong to the class, not to instances:

csharp
1class MathHelper
2{
3 // Static method - called on the class, not an object
4 public static int Add(int a, int b)
5 {
6 return a + b;
7 }
8
9 public static double CircleArea(double radius)
10 {
11 return Math.PI * radius * radius;
12 }
13
14 public static bool IsEven(int number)
15 {
16 return number % 2 == 0;
17 }
18}
19
20// Call static methods on the class name
21int sum = MathHelper.Add(5, 3);
22double area = MathHelper.CircleArea(5);
23bool even = MathHelper.IsEven(10);

Instance vs Static

csharp
1class Counter
2{
3 // Static field - shared by all instances
4 public static int TotalCount { get; private set; } = 0;
5
6 // Instance field - unique to each object
7 public int Id { get; }
8 public string Name { get; set; }
9
10 public Counter(string name)
11 {
12 TotalCount++;
13 Id = TotalCount;
14 Name = name;
15 }
16
17 // Instance method - uses object data
18 public void Display()
19 {
20 Console.WriteLine($"Counter #{Id}: {Name}");
21 }
22
23 // Static method - operates on class-level data
24 public static void ShowTotal()
25 {
26 Console.WriteLine($"Total counters created: {TotalCount}");
27 }
28}
29
30Counter c1 = new Counter("First");
31Counter c2 = new Counter("Second");
32Counter c3 = new Counter("Third");
33
34c1.Display(); // Counter #1: First
35c2.Display(); // Counter #2: Second
36
37Counter.ShowTotal(); // Total counters created: 3

Method Overloading in Classes

csharp
1class Printer
2{
3 public void Print(string message)
4 {
5 Console.WriteLine(message);
6 }
7
8 public void Print(string message, int times)
9 {
10 for (int i = 0; i < times; i++)
11 {
12 Console.WriteLine(message);
13 }
14 }
15
16 public void Print(int number)
17 {
18 Console.WriteLine($"Number: {number}");
19 }
20
21 public void Print(double number, int decimals)
22 {
23 Console.WriteLine(number.ToString($"F{decimals}"));
24 }
25}
26
27Printer p = new Printer();
28p.Print("Hello");
29p.Print("Hi", 3);
30p.Print(42);
31p.Print(3.14159, 2); // 3.14

Methods Calling Other Methods

csharp
1class ShoppingCart
2{
3 private List<decimal> items = new List<decimal>();
4
5 public void AddItem(decimal price)
6 {
7 items.Add(price);
8 }
9
10 public decimal GetSubtotal()
11 {
12 decimal total = 0;
13 foreach (decimal price in items)
14 {
15 total += price;
16 }
17 return total;
18 }
19
20 public decimal GetTax(decimal taxRate = 0.08m)
21 {
22 return GetSubtotal() * taxRate; // Calls GetSubtotal
23 }
24
25 public decimal GetTotal()
26 {
27 return GetSubtotal() + GetTax(); // Calls both methods
28 }
29
30 public void DisplayReceipt()
31 {
32 Console.WriteLine("=== Receipt ===");
33 Console.WriteLine($"Subtotal: {GetSubtotal():C}");
34 Console.WriteLine($"Tax: {GetTax():C}");
35 Console.WriteLine($"Total: {GetTotal():C}");
36 }
37}
38
39ShoppingCart cart = new ShoppingCart();
40cart.AddItem(19.99m);
41cart.AddItem(29.99m);
42cart.AddItem(9.99m);
43cart.DisplayReceipt();

Expression-Bodied Methods

csharp
1class Circle
2{
3 public double Radius { get; set; }
4
5 // Expression-bodied methods
6 public double GetArea() => Math.PI * Radius * Radius;
7 public double GetCircumference() => 2 * Math.PI * Radius;
8 public double GetDiameter() => Radius * 2;
9 public bool IsLargerThan(Circle other) => Radius > other.Radius;
10
11 public override string ToString() => $"Circle with radius {Radius}";
12}

Practical Example

csharp
1class Player
2{
3 public string Name { get; set; }
4 public int Health { get; private set; }
5 public int MaxHealth { get; }
6 public int Level { get; private set; }
7 public int Experience { get; private set; }
8
9 private static int nextId = 1;
10 public int Id { get; }
11
12 public Player(string name, int maxHealth = 100)
13 {
14 Id = nextId++;
15 Name = name;
16 MaxHealth = maxHealth;
17 Health = maxHealth;
18 Level = 1;
19 Experience = 0;
20 }
21
22 public void TakeDamage(int damage)
23 {
24 Health = Math.Max(0, Health - damage);
25 Console.WriteLine($"{Name} takes {damage} damage. Health: {Health}/{MaxHealth}");
26
27 if (Health == 0)
28 {
29 Console.WriteLine($"{Name} has been defeated!");
30 }
31 }
32
33 public void Heal(int amount)
34 {
35 int oldHealth = Health;
36 Health = Math.Min(MaxHealth, Health + amount);
37 int healed = Health - oldHealth;
38 Console.WriteLine($"{Name} healed for {healed}. Health: {Health}/{MaxHealth}");
39 }
40
41 public void GainExperience(int xp)
42 {
43 Experience += xp;
44 Console.WriteLine($"{Name} gained {xp} XP. Total: {Experience}");
45
46 // Level up every 100 XP
47 while (Experience >= Level * 100)
48 {
49 LevelUp();
50 }
51 }
52
53 private void LevelUp()
54 {
55 Level++;
56 Console.WriteLine($"🎉 {Name} reached Level {Level}!");
57 }
58
59 public bool IsAlive() => Health > 0;
60
61 public void DisplayStatus()
62 {
63 Console.WriteLine($"[{Id}] {Name} - Level {Level}");
64 Console.WriteLine($" Health: {Health}/{MaxHealth}");
65 Console.WriteLine($" Experience: {Experience}");
66 }
67}
68
69// Usage
70Player hero = new Player("Hero", 150);
71Player enemy = new Player("Goblin", 50);
72
73hero.DisplayStatus();
74hero.TakeDamage(30);
75hero.Heal(20);
76hero.GainExperience(150); // Should level up
77hero.DisplayStatus();

Summary

In this lesson, you learned:

  • Instance methods operate on object data
  • Static methods belong to the class, not instances
  • Methods can return values and accept parameters
  • Methods can call other methods within the class
  • Overloading allows multiple methods with the same name
  • Expression-bodied syntax works for simple methods

Next, we'll learn about access modifiers for encapsulation.