×

C# Crash Course

Course Home C# Introduction and Setup C# Variables and Data Types C# Console Input and Output C# Operators and Expressions C# Conditional Statements - If and Else C# Switch Statements C# While and Do-While Loops C# For Loops C# Nested Loops C# Methods - Part 1 (Basics) C# Methods - Part 2 (ref, out, and Recursion) C# Arrays C# Number Systems (Binary and Hexadecimal) C# Exception Handling (Try-Catch) C# Random Numbers C# String Methods and Manipulation C# Course Summary and Best Practices


C# Methods - Part 1 (Basics)

What is a Method?

A method (also called a function) is a block of code that performs a specific task. Methods help organize code, reduce repetition, and make programs easier to understand.

Why Use Methods?

Code Reusability: Write once, use many times ✅ Organization: Break large programs into smaller parts ✅ Maintainability: Easier to update and fix ✅ Readability: Code is easier to understand

Basic Method Syntax

static returnType MethodName(parameters)
{
    // Code to execute
    return value;  // If returnType is not void
}

Parts of a Method:

  1. static: Keyword (required for now)
  2. returnType: Type of value returned (or void if none)
  3. MethodName: Name of the method (starts with uppercase)
  4. parameters: Input values (optional)
  5. return: Returns a value (if not void)

Method Without Return Value (void)

Example 1: Simple Greeting

using System;

namespace MethodsBasics
{
    class Program
    {
        static void Main(string[] args)
        {
            PrintGreeting();  // Call the method
            PrintGreeting();  // Can call multiple times

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }

        static void PrintGreeting()
        {
            Console.WriteLine("Hello, welcome to C#!");
        }
    }
}

// Output:
// Hello, welcome to C#!
// Hello, welcome to C#!

Example 2: Print Line

static void Main(string[] args)
{
    Console.WriteLine("Start");
    PrintLine();
    Console.WriteLine("Middle");
    PrintLine();
    Console.WriteLine("End");

    Console.ReadKey();
}

static void PrintLine()
{
    Console.WriteLine("========================");
}

// Output:
// Start
// ========================
// Middle
// ========================
// End

Method With Return Value

Example 1: Get Current Year

static void Main(string[] args)
{
    int iYear = GetCurrentYear();
    Console.WriteLine($"Current year: {iYear}");

    Console.ReadKey();
}

static int GetCurrentYear()
{
    return 2025;
}

Example 2: Calculate Sum

static void Main(string[] args)
{
    int iResult = GetSum();
    Console.WriteLine($"Sum: {iResult}");

    Console.ReadKey();
}

static int GetSum()
{
    int iA = 10;
    int iB = 20;
    int iSum = iA + iB;
    return iSum;
}

Methods With Parameters

Parameters allow you to pass data into methods.

Example 1: Single Parameter

static void Main(string[] args)
{
    PrintMessage("Hello World!");
    PrintMessage("Welcome to C#");
    PrintMessage("Methods are useful!");

    Console.ReadKey();
}

static void PrintMessage(string sMsg)
{
    Console.WriteLine(sMsg);
}

// Output:
// Hello World!
// Welcome to C#
// Methods are useful!

Example 2: Multiple Parameters

static void Main(string[] args)
{
    PrintInfo("Alice", 25);
    PrintInfo("Bob", 30);
    PrintInfo("Charlie", 28);

    Console.ReadKey();
}

static void PrintInfo(string sName, int iAge)
{
    Console.WriteLine($"Name: {sName}, Age: {iAge}");
}

// Output:
// Name: Alice, Age: 25
// Name: Bob, Age: 30
// Name: Charlie, Age: 28

Methods With Parameters and Return Value

Example 1: Add Two Numbers

static void Main(string[] args)
{
    int iResult = Add(5, 3);
    Console.WriteLine($"5 + 3 = {iResult}");

    int iResult2 = Add(10, 20);
    Console.WriteLine($"10 + 20 = {iResult2}");

    Console.ReadKey();
}

static int Add(int iA, int iB)
{
    return iA + iB;
}

// Output:
// 5 + 3 = 8
// 10 + 20 = 30

Example 2: Calculate Rectangle Area

static void Main(string[] args)
{
    double dArea = CalculateArea(5.0, 10.0);
    Console.WriteLine($"Area: {dArea}");

    Console.ReadKey();
}

static double CalculateArea(double dLength, double dWidth)
{
    return dLength * dWidth;
}

Practical Examples from Course

Example 1: Temperature Conversion (From Practical Test 1)

using System;

namespace TemperatureConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            double dCelsius = 40.0;
            double dFahrenheit = 120.0;

            double dCtoF = CelsiusToFahrenheit(dCelsius);
            double dFtoC = FahrenheitToCelsius(dFahrenheit);

            Console.WriteLine($"{dCelsius}°C = {dCtoF:0.0}°F");
            Console.WriteLine($"{dFahrenheit}°F = {dFtoC:0.0}°C");

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }

        static double CelsiusToFahrenheit(double dCelsius)
        {
            return (9.0 / 5) * dCelsius + 32;
        }

        static double FahrenheitToCelsius(double dFahrenheit)
        {
            return (5.0 / 9) * (dFahrenheit - 32);
        }
    }
}

Example 2: Calculator Methods (From Worksheet 2)

using System;

namespace CalculatorMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            double dNum1, dNum2;
            char cOperator;

            dNum1 = GetValidNumber("Enter first number: ");
            dNum2 = GetValidNumber("Enter second number: ");
            cOperator = GetValidOperator();

            double dResult = Calculate(dNum1, dNum2, cOperator);

            Console.WriteLine($"\nResult: {dNum1} {cOperator} {dNum2} = {dResult}");

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }

        static double GetValidNumber(string sPrompt)
        {
            double dNumber;
            bool isValid;

            do
            {
                Console.Write(sPrompt);
                isValid = double.TryParse(Console.ReadLine(), out dNumber);

                if (!isValid)
                {
                    Console.WriteLine("\nInvalid input. Please enter a valid number.\n");
                }
            } while (!isValid);

            return dNumber;
        }

        static char GetValidOperator()
        {
            char cOperator;
            bool isValid;

            do
            {
                Console.Write("\nEnter an operator (+, -, *, /): ");
                isValid = char.TryParse(Console.ReadLine(), out cOperator) && 
                         (cOperator == '+' || cOperator == '-' || 
                          cOperator == '*' || cOperator == '/');

                if (!isValid)
                {
                    Console.WriteLine("\nInvalid operator. Please enter +, -, *, or /.");
                }
            } while (!isValid);

            return cOperator;
        }

        static double Calculate(double dNum1, double dNum2, char cOperator)
        {
            switch (cOperator)
            {
                case '+':
                    return dNum1 + dNum2;
                case '-':
                    return dNum1 - dNum2;
                case '*':
                    return dNum1 * dNum2;
                case '/':
                    if (dNum2 == 0)
                    {
                        Console.WriteLine("\nWarning: Division by zero is not allowed. Returning 0.");
                        return 0;
                    }
                    return dNum1 / dNum2;
                default:
                    Console.WriteLine("\nInvalid operator. Returning 0.");
                    return 0;
            }
        }
    }
}

Example 3: Ticket Pricing Methods (From Practical Test 5)

using System;

namespace TicketPricing
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Movie Theater Ticket Price Calculator");

            Console.Write("Enter your age: ");
            int iAge = ValidateAge(Console.ReadLine());

            if (iAge == -1)
            {
                Console.WriteLine("\nInvalid age.");
                return;
            }

            Console.Write("\nIs the showtime (A)fternoon or (E)vening? Enter A or E: ");
            string sShowtime = Console.ReadLine().ToUpper();

            decimal mPrice = CalculateTicketPrice(iAge, sShowtime);
            DisplayTicketInfo(iAge, sShowtime, mPrice);

            Console.WriteLine("\nPress any key to exit...");
            Console.ReadKey();
        }

        static int ValidateAge(string sInput)
        {
            if (int.TryParse(sInput, out int iAge))
            {
                if (iAge >= 0 && iAge <= 120)
                {
                    return iAge;
                }
            }
            return -1;  // Invalid
        }

        static decimal CalculateTicketPrice(int iAge, string sShowtime)
        {
            decimal mBasePrice;

            if (sShowtime == "A")
            {
                mBasePrice = 8.00m;
            }
            else
            {
                mBasePrice = 12.00m;
            }

            if (iAge <= 12)
            {
                return mBasePrice * 0.60m;  // 40% discount
            }
            else if (iAge >= 65)
            {
                return mBasePrice * 0.75m;  // 25% discount
            }
            else
            {
                return mBasePrice;
            }
        }

        static void DisplayTicketInfo(int iAge, string sShowtime, decimal mPrice)
        {
            string sShowtimeType = (sShowtime == "A") ? "Afternoon" : "Evening";
            string sTicketType = GetTicketType(iAge);

            Console.WriteLine("\nTicket Details:");
            Console.WriteLine($"Age: {iAge}");
            Console.WriteLine($"Showtime: {sShowtimeType}");
            Console.WriteLine($"Ticket Type: {sTicketType}");
            Console.WriteLine($"Price: R{mPrice:0.00}");
        }

        static string GetTicketType(int iAge)
        {
            if (iAge <= 12)
            {
                return "Child";
            }
            else if (iAge >= 65)
            {
                return "Senior";
            }
            else
            {
                return "Adult";
            }
        }
    }
}

Method Naming Conventions

From your course requirements:

Start with uppercase letter: CalculateSum(), not calculateSum()Use descriptive names: GetUserAge(), not Get()Use verbs: CalculateArea(), PrintMessage(), ValidateInput()

// Good method names
static double CalculateArea(double dLength, double dWidth)
static void PrintGreeting()
static int GetAge()
static bool ValidateEmail(string sEmail)

// Bad method names (avoid these)
static double Area(double x, double y)  // Not descriptive
static void print()                      // Lowercase start
static int a()                          // Too short

Calling Methods

Direct Call

PrintMessage("Hello");

Store Result in Variable

int iSum = Add(5, 3);
Console.WriteLine(iSum);

Use Result Directly

Console.WriteLine(Add(5, 3));

Method Calling Another Method

static void Main(string[] args)
{
    MethodA();
}

static void MethodA()
{
    Console.WriteLine("Method A");
    MethodB();  // MethodA calls MethodB
}

static void MethodB()
{
    Console.WriteLine("Method B");
}

// Output:
// Method A
// Method B

Return Statement

Returning Values

static int GetNumber()
{
    return 42;  // Returns integer
}

static string GetName()
{
    return "Alice";  // Returns string
}

static bool IsAdult(int iAge)
{
    return iAge >= 18;  // Returns boolean
}

Early Return

You can return early to exit a method:

static string GetGrade(int iMarks)
{
    if (iMarks >= 80)
    {
        return "A";  // Early return
    }
    else if (iMarks >= 70)
    {
        return "B";
    }
    else if (iMarks >= 60)
    {
        return "C";
    }
    else if (iMarks >= 50)
    {
        return "D";
    }
    else
    {
        return "F";
    }
}

Void Methods Don't Return Values

static void PrintMessage(string sMsg)
{
    Console.WriteLine(sMsg);
    // No return statement needed
}

// Or you can use return to exit early
static void CheckAge(int iAge)
{
    if (iAge < 0)
    {
        Console.WriteLine("Invalid age");
        return;  // Exit method early
    }

    Console.WriteLine($"Valid age: {iAge}");
}

Practice Exercises

Exercise 1: Create IsEven Method

Create a method that takes an integer and returns true if even, false if odd.

Exercise 2: Create GetMax Method

Create a method that takes two integers and returns the larger one.

Exercise 3: Create PrintSquare Method

Create a method that takes a number and prints its square.

Exercise 4: Create CalculateDiscount Method

Create a method that takes a price and discount percentage, returns the final price.

Exercise 5: Create ValidatePassword Method

Create a method that checks if a password is at least 8 characters long.

Common Mistakes to Avoid

Forgetting to return a value:

static int GetSum(int iA, int iB)
{
    int iSum = iA + iB;
    // Missing return! Compile error
}

Correct:

static int GetSum(int iA, int iB)
{
    int iSum = iA + iB;
    return iSum;
}

Wrong parameter order:

static void PrintInfo(string sName, int iAge)
{
    Console.WriteLine($"{sName} is {iAge} years old");
}

// Wrong order!
PrintInfo(25, "Alice");  // ERROR!

Correct:

PrintInfo("Alice", 25);  // Correct order

Not using returned value:

static int Add(int iA, int iB)
{
    return iA + iB;
}

Add(5, 3);  // Result is lost!

Correct:

int iResult = Add(5, 3);  // Store result
Console.WriteLine(iResult);

// Or use directly
Console.WriteLine(Add(5, 3));

Key Takeaways

✅ Methods help organize and reuse code ✅ Use void when method doesn't return a value ✅ Use specific return type when method returns a value ✅ Parameters allow passing data into methods ✅ Method names should start with uppercase ✅ Always return a value if return type is not void ✅ Call methods by name with required parameters


Next Topic: C# Methods - Part 2 (ref, out, and Recursion)