Master C# Programming From Scratch

Clear, interactive, and structured coding lessons designed for absolute beginners.

Methods in C#

What is a Method?

A method is a block of code that performs a specific task. Methods are used to organize code into small, reusable and manageable sections.

Instead of writing the same code multiple times, we can write that code inside a method and call the method whenever it is required. Methods help make programs easier to understand, maintain, test and debug.

Simple Example: If an application needs to display a welcome message at multiple places, we can create one method for the welcome message and call that method whenever required.

Why Do We Use Methods?

  • Code Reusability: Write code once and use it multiple times.
  • Maintainability: Changes can be made in one place.
  • Readability: Large programs can be divided into smaller meaningful blocks.
  • Testing: Individual methods can be tested separately.
  • Debugging: Errors can be located more easily.

Method Syntax

A method generally contains an access modifier, return type, method name, parameters and a method body.

C#
accessModifier returnType MethodName(parameters)
{
    // Code to be executed
}
Main Parts of a Method
Part Purpose
Access Modifier Defines who can access the method.
Return Type Defines the type of value returned by the method.
Method Name The name used to identify and call the method.
Parameters Values that can be passed to the method.
Method Body Contains the statements executed by the method.

Creating a Simple Method

The following method simply displays a welcome message.

C#
using System;
 
static void DisplayMessage()
{
    Console.WriteLine("Welcome to CIIT Training Institute 🤓❤️...!");
}
Calling the Method

Defining a method does not execute it automatically. We need to call the method to execute its code.

C#
using System;
 
static void Main()
{
    DisplayMessage();
}

static void DisplayMessage()
{
    Console.WriteLine("Welcome to CIIT Training Institute 🤓❤️...!");
}
Output: Welcome to CIIT Training Institute 🤓❤️...!

Methods with void Return Type

The void keyword indicates that a method does not return any value to the calling code.

Example
C#
using System;
 
static void PrintName()
{
    Console.WriteLine("Samadhan");
}

PrintName();

Methods with Parameters

Parameters allow us to pass data into a method. A method can accept one or more parameters.

Example
C#
using System;
 
static void GreetUser(string name)
{
    Console.WriteLine($"Welcome, {name}!");
}

GreetUser("Samadhan");
GreetUser("Pradnya");

Here, name is a parameter and the values "Samadhan" and "Prardnya" are arguments passed to the method.

Methods with Multiple Parameters

A method can accept multiple parameters of different or same data types.

C#
using System;
 
static void DisplayStudent(string name, int age)
{
    Console.WriteLine($"Name: {name}");
    Console.WriteLine($"Age: {age}");
}

DisplayStudent("Sejl", 22);

Methods with Return Value

A method can perform some calculation and return a value to the calling code. The return type specifies what type of value the method will return.

Example
C#
using System;
 
static int Add(int a, int b)
{
    return a + b;
}

int result = Add(10, 20);

Console.WriteLine(result);
Output: 30

The return Keyword

The return keyword is used to return a value from a method to the calling code. Once the return statement executes, the method finishes its execution.

C#
using System;
 
static int Square(int number)
{
    return number * number;
}

int result = Square(5);

Console.WriteLine(result);
Output: 25

Different Return Types

Methods can return different types of values such as int, double, string, bool, objects and other data types.

C#
using System;
 
static string GetCourseName()
{
    return ".NET Full Stack Development";
}

static bool IsAdult(int age)
{
    return age >= 18;
}

Console.WriteLine(GetCourseName());
Console.WriteLine(IsAdult(25));

Static Methods

A static method belongs to the class rather than an object. It can be called using the class name without creating an object.

C#
using System;
 
class Calculator
{
    public static int Add(int a, int b)
    {
        return a + b;
    }
}

int result = Calculator.Add(10, 20);

Console.WriteLine(result);

Instance Methods

An instance method belongs to an object of a class. To call an instance method, we first create an object of that class.

C#
using System;
 
class Student
{
    public void DisplayName()
    {
        Console.WriteLine("Student: Rahul");
    }
}

Student student = new Student();

student.DisplayName();

Value Parameters

By default, C# passes value-type parameters by value. This means the method receives a copy of the original value.

C#
using System;
static void ChangeValue(int number)
{
    number = 100;
}

int value = 10;

ChangeValue(value);

Console.WriteLine(value);
Output: 10
The original value is not changed because the method received a copy of the value.

Optional Parameters

Optional parameters allow a method to have default values. The caller does not need to provide a value for an optional parameter.

C#
using System;
 
static void Greet(string name = "Guest")
{
    Console.WriteLine($"Hello, {name}");
}

Greet();
Greet("Amit");

If no argument is supplied, the default value "Guest" is used.

Named Arguments

Named arguments allow us to specify parameter names while calling a method. This can make method calls easier to understand.

C#
using System;
 
static void DisplayEmployee(string name, int age)
{
    Console.WriteLine($"Name: {name}");
    Console.WriteLine($"Age: {age}");
}

DisplayEmployee(age: 25, name: "Sneha");

Expression-Bodied Methods

C# provides a shorter syntax for methods that contain a single expression. The => operator is used for this purpose.

C#
using System;
 
static int Multiply(int a, int b) => a * b;

Console.WriteLine(Multiply(5, 4));
Output: 20

Example 🌍❤️

In real-world applications, methods are used to divide business logic into reusable operations. For example, an application may have separate methods for calculating salary, validating users, calculating marks, processing payments, or retrieving data.

C#
using System;
 static double CalculateDiscount(double price, double discountPercentage)
{
    double discount = price * discountPercentage / 100;
    return price - discount;
}

double finalPrice = CalculateDiscount(1000, 10);

Console.WriteLine($"Final Price: {finalPrice}");
Output: Final Price: 900

Method Naming Best Practices

  • Use meaningful and descriptive method names.
  • Use PascalCase for method names in C#.
  • A method should generally perform one clear responsibility.
  • Avoid unnecessarily long methods.
  • Use parameters when a method needs input.
  • Use a suitable return type when a method needs to return a result.

Common Mistakes to Avoid

  • Defining a method but forgetting to call it.
  • Using the wrong return type.
  • Forgetting the return statement when a value is expected.
  • Passing arguments in the wrong order.
  • Creating methods that are too large and difficult to maintain.
Summary

Methods are reusable blocks of code that perform specific tasks. They help improve code organization, readability, reusability, testing and maintenance. A method can accept parameters and can return a value. C# supports static methods, instance methods, optional parameters, named arguments and expression-bodied methods.

Practice Questions

  1. Create a method to display your name.
  2. Create a method that accepts two numbers and prints their sum.
  3. Create a method that returns the square of a number.
  4. Create a method that checks whether a number is even or odd.
  5. Create a method that accepts student name and marks and displays them.
  6. Create a method to calculate the final price after applying a discount.
  7. Create a method using an optional parameter.
  8. Create an expression-bodied method to calculate multiplication.
  9. Explain the difference between static and instance methods.
  10. Explain the difference between a parameter and an argument.