techmore.in

C# - Methods

In C#, methods are blocks of code that perform a specific task. They are used to encapsulate logic, improve code reusability, and maintainability. Methods are defined within a class or struct and can be called from other parts of the code. Here’s a detailed overview of methods in C#:

1. Defining a Method

To define a method, specify its access modifier, return type, method name, and parameters (if any). The method body contains the code that performs the task.

Syntax:

csharp
access_modifier return_type MethodName(parameters) { // Method body }

Example:

csharp
public int Add(int a, int b) { return a + b; }

2. Calling a Method

You call a method by using its name and providing the necessary arguments.

Example:

csharp
int sum = Add(5, 3); // Calls the Add method with arguments 5 and 3 Console.WriteLine(sum); // Outputs: 8

3. Method Overloading

Method overloading allows you to define multiple methods with the same name but different parameters (different number or type).

Example:

csharp
public int Add(int a, int b) { return a + b; } public double Add(double a, double b) { return a + b; } public int Add(int a, int b, int c) { return a + b + c; }

4. Parameters

Methods can have parameters to accept input values. You can also specify default values for parameters.

Example:

csharp
public void Greet(string name, string greeting = "Hello") { Console.WriteLine($"{greeting}, {name}!"); } Greet("Alice"); // Uses default greeting "Hello" Greet("Bob", "Hi"); // Uses specified greeting "Hi"

5. Return Types

Methods can return a value of a specific type, or they can return void if no value is needed.

Example:

csharp
public string GetGreeting() { return "Hello, World!"; } public void PrintGreeting() { Console.WriteLine("Hello, World!"); }

6. Method Scope and Accessibility

The access modifier determines the visibility of the method. Common access modifiers include public, private, protected, and internal.

  • public: Accessible from anywhere.
  • private: Accessible only within the same class or struct.
  • protected: Accessible within the same class or derived classes.
  • internal: Accessible within the same assembly.

Example:

csharp
public class MyClass { public void PublicMethod() { // Accessible from outside this class } private void PrivateMethod() { // Accessible only within this class } }

7. Static Methods

Static methods belong to the class itself rather than an instance of the class. They can be called without creating an instance of the class.

Syntax:

csharp
public static void StaticMethod() { // Method body }

Example:

csharp
public static class MathHelper { public static int Square(int number) { return number * number; } } int result = MathHelper.Square(4); // Calls the static method

8. Instance Methods

Instance methods belong to an instance of a class. They can access instance variables and other instance methods.

Example:

csharp
public class Calculator { public int Multiply(int x, int y) { return x * y; } } Calculator calc = new Calculator(); int product = calc.Multiply(4, 5); // Calls the instance method

9. Method Parameters: Ref and Out

  • ref: Allows a method to modify the value of a parameter. The parameter must be initialized before it is passed.
  • out: Similar to ref, but the parameter does not need to be initialized before being passed. The method must assign a value to the parameter before returning.

Example:

csharp
public void Increment(ref int number) { number++; } public void GetValues(out int a, out int b) { a = 10; b = 20; } int x = 5; Increment(ref x); // x is now 6 GetValues(out int val1, out int val2); // val1 is 10, val2 is 20

10. Method Chaining

Method chaining is a technique where multiple methods are called on the same object in a single statement.

Example:

csharp
public class StringBuilder { private string text = ""; public StringBuilder Append(string str) { text += str; return this; // Returns the same object to allow chaining } public void Print() { Console.WriteLine(text); } } new StringBuilder() .Append("Hello") .Append(", ") .Append("World!") .Print(); // Outputs: Hello, World!

11. Asynchronous Methods

Asynchronous methods use the async keyword and return a Task or Task<T> to perform operations asynchronously.

Syntax:

csharp
public async Task<string> FetchDataAsync() { await Task.Delay(1000); // Simulate async operation return "Data"; }

Example:

csharp
public async Task RunAsync() { string result = await FetchDataAsync(); Console.WriteLine(result); // Outputs: Data }

Summary

Methods in C# are crucial for organizing and structuring code. They allow you to encapsulate logic, reuse code, and manage complexity. Understanding how to define, call, overload, and use various types of methods—including static, instance, and asynchronous methods—will help you write cleaner and more efficient C# code. Methods with parameters, return types, and advanced features like ref, out, and method chaining further enhance your ability to create robust applications.