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

Why methods are needed in C Sharp (C#)

Choose your learning style9 modes available
Introduction

Methods help us organize code into small, reusable parts. They make programs easier to read, fix, and reuse.

When you want to repeat the same task many times without writing the same code again.
When you want to break a big problem into smaller, easier steps.
When you want to fix or improve one part of the program without changing everything.
When you want to share code with others or use it in different programs.
When you want your program to be clear and easy to understand.
Syntax
C Sharp (C#)
returnType MethodName(parameters) {
    // code to do something
    return value; // if needed
}

returnType is the type of value the method gives back (like int, string, or void if nothing).

parameters are inputs the method needs to work, inside parentheses.

Examples
A method that says hello and does not return anything.
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;
}
Sample Program

This program uses two methods: one to say hello and one to add numbers. It shows how methods keep code neat and reusable.

C Sharp (C#)
using System;

class Program {
    static void SayHello() {
        Console.WriteLine("Hello, friend!");
    }

    static int Add(int x, int y) {
        return x + y;
    }

    static void Main() {
        SayHello();
        int sum = Add(3, 4);
        Console.WriteLine($"Sum is {sum}");
    }
}
OutputSuccess
Important Notes

Methods help avoid repeating the same code in many places.

Using methods makes it easier to find and fix mistakes.

Methods can take inputs and give back results, making programs flexible.

Summary

Methods organize code into small, clear parts.

They let you reuse code without copying it.

Methods make programs easier to read and fix.