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:
csharp1class Dog2{3 public string Name { get; set; }4 public int Age { get; set; }56 // Instance method7 public void Bark()8 {9 Console.WriteLine($"{Name} says: Woof!");10 }1112 // Instance method using object data13 public void DisplayInfo()14 {15 Console.WriteLine($"Name: {Name}, Age: {Age}");16 }17}1819Dog myDog = new Dog { Name = "Buddy", Age = 3 };20myDog.Bark(); // Buddy says: Woof!21myDog.DisplayInfo(); // Name: Buddy, Age: 3
Methods with Return Values
csharp1class Rectangle2{3 public double Width { get; set; }4 public double Height { get; set; }56 public double GetArea()7 {8 return Width * Height;9 }1011 public double GetPerimeter()12 {13 return 2 * (Width + Height);14 }1516 public bool IsSquare()17 {18 return Width == Height;19 }20}2122Rectangle rect = new Rectangle { Width = 5, Height = 5 };23Console.WriteLine($"Area: {rect.GetArea()}"); // 2524Console.WriteLine($"Perimeter: {rect.GetPerimeter()}"); // 2025Console.WriteLine($"Is square: {rect.IsSquare()}"); // True
Methods with Parameters
csharp1class BankAccount2{3 public string Owner { get; set; }4 public decimal Balance { get; private set; }56 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 }1415 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 }2627 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}3637BankAccount alice = new BankAccount { Owner = "Alice" };38BankAccount bob = new BankAccount { Owner = "Bob" };3940alice.Deposit(1000);41alice.Transfer(bob, 250);
Static Methods
Static methods belong to the class, not to instances:
csharp1class MathHelper2{3 // Static method - called on the class, not an object4 public static int Add(int a, int b)5 {6 return a + b;7 }89 public static double CircleArea(double radius)10 {11 return Math.PI * radius * radius;12 }1314 public static bool IsEven(int number)15 {16 return number % 2 == 0;17 }18}1920// Call static methods on the class name21int sum = MathHelper.Add(5, 3);22double area = MathHelper.CircleArea(5);23bool even = MathHelper.IsEven(10);
Instance vs Static
csharp1class Counter2{3 // Static field - shared by all instances4 public static int TotalCount { get; private set; } = 0;56 // Instance field - unique to each object7 public int Id { get; }8 public string Name { get; set; }910 public Counter(string name)11 {12 TotalCount++;13 Id = TotalCount;14 Name = name;15 }1617 // Instance method - uses object data18 public void Display()19 {20 Console.WriteLine($"Counter #{Id}: {Name}");21 }2223 // Static method - operates on class-level data24 public static void ShowTotal()25 {26 Console.WriteLine($"Total counters created: {TotalCount}");27 }28}2930Counter c1 = new Counter("First");31Counter c2 = new Counter("Second");32Counter c3 = new Counter("Third");3334c1.Display(); // Counter #1: First35c2.Display(); // Counter #2: Second3637Counter.ShowTotal(); // Total counters created: 3
Method Overloading in Classes
csharp1class Printer2{3 public void Print(string message)4 {5 Console.WriteLine(message);6 }78 public void Print(string message, int times)9 {10 for (int i = 0; i < times; i++)11 {12 Console.WriteLine(message);13 }14 }1516 public void Print(int number)17 {18 Console.WriteLine($"Number: {number}");19 }2021 public void Print(double number, int decimals)22 {23 Console.WriteLine(number.ToString($"F{decimals}"));24 }25}2627Printer p = new Printer();28p.Print("Hello");29p.Print("Hi", 3);30p.Print(42);31p.Print(3.14159, 2); // 3.14
Methods Calling Other Methods
csharp1class ShoppingCart2{3 private List<decimal> items = new List<decimal>();45 public void AddItem(decimal price)6 {7 items.Add(price);8 }910 public decimal GetSubtotal()11 {12 decimal total = 0;13 foreach (decimal price in items)14 {15 total += price;16 }17 return total;18 }1920 public decimal GetTax(decimal taxRate = 0.08m)21 {22 return GetSubtotal() * taxRate; // Calls GetSubtotal23 }2425 public decimal GetTotal()26 {27 return GetSubtotal() + GetTax(); // Calls both methods28 }2930 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}3839ShoppingCart cart = new ShoppingCart();40cart.AddItem(19.99m);41cart.AddItem(29.99m);42cart.AddItem(9.99m);43cart.DisplayReceipt();
Expression-Bodied Methods
csharp1class Circle2{3 public double Radius { get; set; }45 // Expression-bodied methods6 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;1011 public override string ToString() => $"Circle with radius {Radius}";12}
Practical Example
csharp1class Player2{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; }89 private static int nextId = 1;10 public int Id { get; }1112 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 }2122 public void TakeDamage(int damage)23 {24 Health = Math.Max(0, Health - damage);25 Console.WriteLine($"{Name} takes {damage} damage. Health: {Health}/{MaxHealth}");2627 if (Health == 0)28 {29 Console.WriteLine($"{Name} has been defeated!");30 }31 }3233 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 }4041 public void GainExperience(int xp)42 {43 Experience += xp;44 Console.WriteLine($"{Name} gained {xp} XP. Total: {Experience}");4546 // Level up every 100 XP47 while (Experience >= Level * 100)48 {49 LevelUp();50 }51 }5253 private void LevelUp()54 {55 Level++;56 Console.WriteLine($"🎉 {Name} reached Level {Level}!");57 }5859 public bool IsAlive() => Health > 0;6061 public void DisplayStatus()62 {63 Console.WriteLine($"[{Id}] {Name} - Level {Level}");64 Console.WriteLine($" Health: {Health}/{MaxHealth}");65 Console.WriteLine($" Experience: {Experience}");66 }67}6869// Usage70Player hero = new Player("Hero", 150);71Player enemy = new Player("Goblin", 50);7273hero.DisplayStatus();74hero.TakeDamage(30);75hero.Heal(20);76hero.GainExperience(150); // Should level up77hero.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.