C# Tutorial
C# String
C# Array
C# Flow Control
C# Class and Object
C# Inheritance
C# Interface
C# Collection
C# Generic
C# File I/O
C# Delegate and Event
C# Exception
C# Process and Thread
C# ADO.NET Database Operations
In this tutorial, we will learn about methods in C#, which are an essential part of object-oriented programming. Methods are used to perform operations, encapsulate functionality, and enhance code reusability and readability.
A method is a block of code that performs a specific task or operation. Methods can take input parameters and return a value. Methods are declared inside a class or struct and are associated with an object or the class itself.
Here's a simple method declaration:
public int Add(int a, int b) { return a + b; }
In this example, the Add
method takes two integer parameters, a
and b
, and returns their sum as an integer.
A method declaration consists of several components:
Access Modifier: The access modifier determines the visibility of the method. The most common access modifiers are public
, private
, protected
, and internal
.
Return Type: The return type specifies the type of the value the method returns. If the method does not return a value, use the void
keyword.
Method Name: The method name is an identifier that represents the name of the method. It should follow standard C# naming conventions, starting with a capital letter and using camel case.
Parameters: Parameters are variables that are passed into the method when it is called. They are enclosed in parentheses and separated by commas. If the method does not take any parameters, use an empty pair of parentheses.
Method Body: The method body is a block of code enclosed in curly braces {}
that contains the statements to be executed when the method is called.
To call a method, you need to create an object of the class containing the method and use the object to invoke the method:
public class Calculator { public int Add(int a, int b) { return a + b; } } class Program { static void Main(string[] args) { Calculator calculator = new Calculator(); int result = calculator.Add(3, 5); Console.WriteLine(result); // Output: 8 } }
In this example, we create an object of the Calculator
class and call the Add
method using the object.
Static methods are methods that are associated with the class itself rather than an instance of the class. To declare a static method, use the static
keyword:
public class Calculator { public static int Multiply(int a, int b) { return a * b; } }
To call a static method, use the class name instead of an object:
int result = Calculator.Multiply(3, 5); Console.WriteLine(result); // Output: 15
This tutorial introduces methods in C#, which are an essential part of object-oriented programming. Methods are used to perform operations, encapsulate functionality, and enhance code reusability and readability. Understanding methods and how to use them effectively is crucial for writing well-organized and maintainable code in C#.
How to define methods in C#
Methods in C# are defined using the method
keyword, specifying the return type, method name, and parameter list:
// Method definition int Add(int a, int b) { return a + b; }
Returning values from methods in C#
Methods can return values using the return
keyword:
// Method with return value int Multiply(int a, int b) { return a * b; }
Void methods in C#
Void methods don't return a value:
// Void method void DisplayMessage(string message) { Console.WriteLine(message); }
Parameters in C# methods
Methods can have parameters:
// Method with parameters void PrintInfo(string name, int age) { Console.WriteLine($"Name: {name}, Age: {age}"); }
Method overloading in C#
Method overloading involves defining multiple methods with the same name but different parameter lists:
void DisplayInfo(string name) { Console.WriteLine($"Name: {name}"); } void DisplayInfo(string name, int age) { Console.WriteLine($"Name: {name}, Age: {age}"); }
C# static methods
Static methods belong to the class rather than an instance:
// Static method public static int Square(int number) { return number * number; }
Access modifiers in C# methods
Access modifiers control the visibility of methods:
// Public method public void PrintMessage(string message) { Console.WriteLine(message); }
Recursive methods in C#
Recursive methods call themselves:
// Recursive method int Factorial(int n) { if (n == 0 || n == 1) return 1; else return n * Factorial(n - 1); }
Exception handling in C# methods
Methods can handle exceptions using try
, catch
, and finally
blocks:
// Method with exception handling int Divide(int a, int b) { try { return a / b; } catch (DivideByZeroException ex) { Console.WriteLine($"Error: {ex.Message}"); return 0; } }
Extension methods in C#
Extension methods allow adding new methods to existing types:
public static class StringExtensions { public static string Reverse(this string input) { char[] charArray = input.ToCharArray(); Array.Reverse(charArray); return new string(charArray); } }
Lambda expressions and methods in C#
Lambda expressions can define inline methods:
// Lambda expression as a method Func<int, int, int> add = (a, b) => a + b;
C# method chaining
Method chaining involves calling multiple methods in a sequence:
// Method chaining string result = "Hello, World!".ToUpper().Substring(0, 5).Replace(",", "!");