0
0
C Sharp (C#)programming~5 mins

Method declaration and calling in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Methods help you organize your code into small, reusable actions. You declare a method to define what it does, and call it to use it.

When you want to repeat the same task multiple times without rewriting code.
When you want to break a big problem into smaller, easier steps.
When you want to make your code cleaner and easier to read.
When you want to reuse code in different parts of your program.
When you want to test parts of your program separately.
Syntax
C Sharp (C#)
returnType MethodName(parameters) {
    // code to run
}

returnType is the type of value the method gives back (use void if it returns nothing).

parameters are inputs the method can use, separated by commas.

Examples
A method that prints "Hello!" and returns nothing.
C Sharp (C#)
void SayHello() {
    Console.WriteLine("Hello!");
}
A method that adds two numbers and returns the result.
C Sharp (C#)
int Add(int a, int b) {
    return a + b;
}
A method that returns a name as a string.
C Sharp (C#)
string GetName() {
    return "Alice";
}
Sample Program

This program declares two methods: Greet which prints a welcome message, and Multiply which returns the product of two numbers. The Main method calls both methods to show how they work.

C Sharp (C#)
using System;

class Program {
    static void Greet() {
        Console.WriteLine("Welcome to the program!");
    }

    static int Multiply(int x, int y) {
        return x * y;
    }

    static void Main(string[] args) {
        Greet();
        int result = Multiply(4, 5);
        Console.WriteLine($"4 times 5 is {result}");
    }
}
OutputSuccess
Important Notes

Methods must be declared inside a class in C#.

Use static keyword if you want to call the method without creating an object.

Method names usually start with a capital letter by convention.

Summary

Methods let you group code to do specific tasks.

Declare a method with a return type, name, and optional parameters.

Call a method by its name and provide any needed inputs.