Letβs go over methods within classes in C# β an essential concept in object-oriented programming.
π 1. What Are Methods in Classes?
-
A method is a function defined inside a class.
-
It represents behavior or actions that an object of the class can perform.
-
Methods can access fields and properties of the class.
π 2. Basic Syntax
[access_modifier] [return_type] MethodName([parameters])
{
// Method body
}-
access_modifier β
public,private, etc. (who can access the method) -
return_type β data type the method returns (
voidif nothing is returned) -
parameters β optional input values
π 3. Example: Method in a Class
public class Person
{
public string Name;
public int Age;
// Method
public void Greet()
{
Console.WriteLine($"Hello, my name is {Name} and I am {Age} years old.");
}
}
// Usage
Person person = new Person();
person.Name = "Alice";
person.Age = 25;
person.Greet(); // Hello, my name is Alice and I am 25 years old.-
Greet()is a method inside the class -
It can access Name and Age of the object
π 4. Methods with Parameters and Return Values
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
// Usage
Calculator calc = new Calculator();
int result = calc.Add(5, 3); // 8-
Add(int a, int b)has parameters -
Returns a value using
return
π 5. Static vs Instance Methods. Also See Difference Between Instance and Static Methods
-
Instance Methods
-
Called on an object
-
Can access instance fields and properties
-
public void DisplayName()
{
Console.WriteLine(Name);
}-
Static Methods
-
Belong to the class itself, not an object
-
Cannot access instance fields directly
-
public static int Multiply(int a, int b)
{
return a * b;
}
// Usage
int result = Calculator.Multiply(2, 3); // 6π 6. Access Modifiers for Methods
| Modifier | Description |
|---|---|
| public | Accessible anywhere |
| private | Accessible only inside the class |
| protected | Accessible in derived classes |
| internal | Accessible within the same assembly |
| protected internal | Accessible in derived classes or same assembly |
π 7. Method Overloading
- Methods in a class can have same name but different parameters
public int Add(int a, int b) => a + b;
public double Add(double a, double b) => a + b;- Compiler picks the correct method based on arguments provided
π 8. Summary
| Concept | Description |
|---|---|
| Method | Function inside a class representing behavior |
| Instance vs Static | Instance = called on object; Static = called on class |
| Parameters | Input values for the method |
| Return Type | Value returned by the method (void if none) |
| Overloading | Multiple methods with same name but different parameters |
| Access Modifier | Controls visibility (public, private, etc.) |
β Tip:
-
Methods should do one specific task.
-
Use instance methods for object-specific behavior, static methods for general utilities.
-
Combine methods with properties and fields to make classes powerful and encapsulated.