07. Methods in C#
Level: Beginner
- What a method is
- Why methods are useful
- Create a method with no return value
- Create a method with parameters
- Create a method that returns a value
- Reuse methods for marks, grades, and reports
- Avoid common method mistakes
In the previous articles, you wrote code directly in Program.cs.
When code grows, writing everything in one place becomes messy.
Methods help us organize code into small reusable blocks.
The Problem: Repeating the Same Code
Imagine you need to print student details for many students.
Without methods:
Console.WriteLine("Name: Sahasra");
Console.WriteLine("Class: 10-A");
Console.WriteLine("Result: Pass");
Console.WriteLine("Name: Priya");
Console.WriteLine("Class: 10-A");
Console.WriteLine("Result: Pass");
This repeats the same pattern.
With a method:
PrintStudent("Sahasra", "10-A", "Pass");
PrintStudent("Priya", "10-A", "Pass");
Cleaner and reusable.
What is a Method?
A method is a named block of code that performs one job.
static void SayHello()
{
Console.WriteLine("Hello C#");
}
To run the method, call it:
SayHello();
Method Syntax
static returnType MethodName(parameters)
{
// code
}
| Part | Meaning |
|---|---|
static | Used for beginner console examples |
returnType | What the method gives back |
MethodName | Name of the method |
parameters | Inputs to the method |
{ } | Method body |
Quick Definitions
- Method - Named block of reusable code
- Parameter - Input to a method (defined in method signature)
- Argument - Value passed to method when called
- Return value - Output that method gives back
- Return type - Data type of the return value
- Void - Method returns nothing
- Static - Method belongs to the program itself (not an object)
- Scope - Where a variable can be used
- Composition - Multiple methods working together
Understanding the static Keyword
For beginners: static means the method belongs to the program itself, not to an individual object.
In beginner console apps:
- All methods are
static - All methods belong to "Program"
- You call them directly by name
static void SayHello()
{
Console.WriteLine("Hello");
}
SayHello(); // Call directly (because it's static)
Don't worry: You'll understand static deeply in Article 08 (Classes & Objects) when you create instances of classes. For now: all methods are static in console apps.
How Methods Work: Visual Flow
When you call a method:
Main Program
|
v
PrintWelcome(); <- Method call
|
v
Enter method -> PrintWelcome
|
v
Execute code -> Console.WriteLine("Welcome to SMS")
|
v
Return to caller
|
v
Continue in Main Program
Key: When method runs, main program WAITS. When method finishes (return), main program continues.
Step 1: void Method
void means the method does not return a value.
Example:
static void PrintWelcome()
{
Console.WriteLine("Welcome to School Management System");
}
PrintWelcome();
Use void when the method only performs an action, like printing.
Step 2: Method with Parameters
Parameters are input values.
static void PrintStudent(string name, string className, string result)
{
Console.WriteLine("=== Student Details ===");
Console.WriteLine($"Name: {name}");
Console.WriteLine($"Class: {className}");
Console.WriteLine($"Result: {result}");
}
PrintStudent("Sahasra Kumar", "10-A", "Pass");
PrintStudent("Priya Sharma", "10-A", "Pass");
Here:
| Parameter | Example value |
|---|---|
name | "Sahasra Kumar" |
className | "10-A" |
result | "Pass" |
Parameters vs Arguments
Parameters are written in the method definition.
Arguments are actual values passed during the method call.
static void PrintName(string name)
{
Console.WriteLine(name);
}
PrintName("Sahasra");
| Word | Example |
|---|---|
| Parameter | string name |
| Argument | "Sahasra" |
Step 3: Method with Return Value
Some methods calculate and return a result.
Example: calculate total marks.
static int CalculateTotal(int english, int maths, int science)
{
int total = english + maths + science;
return total;
}
int totalMarks = CalculateTotal(80, 90, 70);
Console.WriteLine($"Total: {totalMarks}");
return sends the value back to the caller.
Step 4: Calculate Percentage Method
static double CalculatePercentage(int totalMarks, int maxMarks)
{
double percentage = (double)totalMarks / maxMarks * 100;
return percentage;
}
int total = 424;
double percentage = CalculatePercentage(total, 500);
Console.WriteLine($"Percentage: {percentage:F2}");
Step 5: Get Result Method
static string GetResult(double percentage)
{
if (percentage >= 35)
{
return "Pass";
}
return "Fail";
}
string result = GetResult(84.8);
Console.WriteLine(result);
Important:
When return runs, method stops immediately.
Step 6: Get Grade Method
static string GetGrade(double percentage)
{
if (percentage >= 90)
{
return "A+";
}
else if (percentage >= 80)
{
return "A";
}
else if (percentage >= 70)
{
return "B";
}
else if (percentage >= 60)
{
return "C";
}
else if (percentage >= 35)
{
return "D";
}
return "F";
}
Call it:
string grade = GetGrade(84.8);
Console.WriteLine($"Grade: {grade}");
Step 7: Method with Array Parameter
Methods can receive arrays also.
static int CalculateTotal(int[] marks)
{
int total = 0;
foreach (int mark in marks)
{
total += mark;
}
return total;
}
int[] studentMarks = { 82, 91, 78, 85, 88 };
int total = CalculateTotal(studentMarks);
Console.WriteLine($"Total: {total}");
Full Example: Report Card Using Methods
Expected output:
=== Report Card ===
Name: Sahasra Kumar
Class: 10-A
Total: 424/500
Percentage: 84.80
Grade: A
Result: Pass
Method Naming Rules
Use meaningful action names.
| Good Name | Meaning |
|---|---|
CalculateTotal | Calculates a total |
CalculatePercentage | Calculates percentage |
GetGrade | Returns grade |
GetResult | Returns pass/fail |
PrintReportCard | Prints report card |
IsEligibleForExam | Returns true/false |
Avoid names like:
static int DoIt()
static string Get()
static void Method1()
Small Note: Default Parameters
Default parameters give a value when the caller does not pass one.
static void EnrollStudent(string name, string className, string section = "A")
{
Console.WriteLine($"{name} enrolled in {className}-{section}");
}
EnrollStudent("Sahasra", "10");
EnrollStudent("Priya", "10", "B");
Output:
Sahasra enrolled in 10-A
Priya enrolled in 10-B
Use default parameters only when the default value is obvious.
Small Note: Method Overloading
Method overloading means same method name with different parameters.
static void PrintStudent(string name)
{
Console.WriteLine(name);
}
static void PrintStudent(string name, string className)
{
Console.WriteLine($"{name} - {className}");
}
PrintStudent("Sahasra");
PrintStudent("Sahasra", "10-A");
Learn the basic method concept first. Overloading becomes more useful later.
Quick Reference
| Need | Method Type |
|---|---|
| Print something | void method |
| Calculate and send value back | return method |
| Send input to method | parameters |
| Reuse repeated code | method |
| Return true/false | bool method |
When You'll Use This in SMS
Methods organize SMS features.
Grade calculation:
GetGrade(84.8) -> "A"
Fee calculation:
CalculateBalance(30000, 15000) -> 15000
Report generation:
PrintReportCard("Sahasra", marks) -> Full report printed
Eligibility check:
IsEligible(hasPaid, hasAttended) -> true/false
Real impact:
- Methods organize code into features
- Same method used for all students = consistency
- Change method once = affects entire SMS
- Production SMS has thousands of methods, all working together
Try This Now
Run the report card example above. Then experiment:
- Change student name to your name
- Change marks:
int[] yourMarks = { 90, 85, 88 }; - Run and see your own report card
- Create new method: CalculateAttendancePercentage()
See how methods make code reusable for any student.
Methods explained: creating, calling, parameters, return values. Video coming soon. Subscribe to NexCoding YouTube for updates.
Common Mistakes
Mistake 1: Method says it returns value but does not return
Wrong:
static string GetResult(double percentage)
{
if (percentage >= 35)
{
Console.WriteLine("Pass");
}
}
Correct:
static string GetResult(double percentage)
{
if (percentage >= 35)
{
return "Pass";
}
return "Fail";
}
Mistake 2: Wrong return type
Wrong:
static int GetResult()
{
return "Pass";
}
Correct:
static string GetResult()
{
return "Pass";
}
Mistake 3: Forgetting to call the method
Wrong:
static void PrintWelcome()
{
Console.WriteLine("Welcome");
}
This only defines the method. It does not run.
Correct:
PrintWelcome();
Mistake 4: Doing too many things in one method
Avoid one huge method that calculates, prints, reads input, saves data, and validates everything.
Better:
CalculateTotal
CalculatePercentage
GetGrade
PrintReportCard
Best Practices
- One method should do one clear job.
- Use meaningful method names.
- Use parameters instead of duplicate code.
- Return values when caller needs the result.
- Use
voidonly when no result is needed. - Keep methods small and readable.
- Test one method at a time.
- Avoid advanced method features until basics are clear.
Practice Task
Create these methods:
CalculateBalance(totalFees, paidAmount)
GetFeeStatus(balance)
PrintFeeReport(studentName, totalFees, paidAmount)
Rules:
- Balance = total fees - paid amount
- If balance is 0, status is
Paid - If balance is greater than 0, status is
Pending
Starter:
static decimal CalculateBalance(decimal totalFees, decimal paidAmount)
{
return totalFees - paidAmount;
}
static string GetFeeStatus(decimal balance)
{
if (balance == 0)
{
return "Paid";
}
return "Pending";
}
static void PrintFeeReport(string studentName, decimal totalFees, decimal paidAmount)
{
decimal balance = CalculateBalance(totalFees, paidAmount);
string status = GetFeeStatus(balance);
Console.WriteLine("=== Fee Report ===");
Console.WriteLine($"Student: {studentName}");
Console.WriteLine($"Total Fees: {totalFees}");
Console.WriteLine($"Paid Amount: {paidAmount}");
Console.WriteLine($"Balance: {balance}");
Console.WriteLine($"Status: {status}");
}
PrintFeeReport("Priya Sharma", 40000.00m, 25000.00m);
Quick Revision
| Question | Answer |
|---|---|
| What is a method? | A reusable block of code |
What does void mean? | Method returns nothing |
| What are parameters? | Inputs to a method |
What does return do? | Sends value back and stops method |
| Why use methods? | Reuse code and organize logic |
| What should method names be? | Clear action names |
A method is a reusable block of code that performs one job.
Example:
static void PrintWelcome()
{
Console.WriteLine("Welcome");
}
Call it:
PrintWelcome();
void means the method does not return a value.
A return type like int, string, or bool means the method gives a value back.
Example:
static void PrintName(string name)
{
Console.WriteLine(name);
}
static string GetResult(double percentage)
{
return percentage >= 35 ? "Pass" : "Fail";
}
Parameters are inputs in the method definition.
Arguments are actual values passed during the call.
static void PrintStudent(string name)
{
Console.WriteLine(name);
}
PrintStudent("Sahasra");
string name is a parameter.
"Sahasra" is an argument.
We use methods to:
- Avoid duplicate code
- Organize logic
- Reuse code
- Make code easier to test
- Make programs easier to read
When return runs, the method stops immediately and sends a value back.
Example:
static string GetResult(double percentage)
{
if (percentage >= 35)
{
return "Pass";
}
return "Fail";
}
Method overloading means using the same method name with different parameters.
Example:
static void PrintStudent(string name)
{
Console.WriteLine(name);
}
static void PrintStudent(string name, string className)
{
Console.WriteLine($"{name} - {className}");
}
The compiler chooses the correct method based on arguments.
Use ChatGPT, Claude, or Copilot to go deeper on C# methods. Try these prompts:
"Explain C# methods using school report card examples""Give me 10 beginner practice questions for methods""Explain void, parameters, arguments, and return values simply""Quiz me with 5 beginner questions about C# methods"
💡 Tip: After reading this article, paste your own code into AI and ask "What could go wrong here and why?" — fastest way to find edge cases and deepen understanding.