C# Methods

Learn via video courses
Topics Covered

Overview

A method in C# is a fundamental building block of code that encapsulates a specific set of instructions. It enables you to perform tasks, manipulate data, or return values within a program. Methods in C# promote modularity and reusability by compartmentalizing functionality. They consist of a name, optional parameters, a return type, and a method body containing the executable statements. You can call a method multiple times from various parts of your program, promoting efficient code organization and maintenance. By utilizing types of methods in C#, such as static, instance, method with parameters, method overloading, and more, C# programs become more structured and easier to understand, facilitating the implementation of complex logic systematically. A method consists of a method signature, which includes its name, return type (or "void" if it doesn't return anything), and any parameters it accepts. The method body contains the actual code to be executed when the method is called. By defining methods in C#, developers can write modular code that can be easily maintained and modified.

Create a Method

A method is established using its designated name, succeeded by parentheses (). While C# offers predefined methods like Main(), you also can generate your methods to execute specific tasks.

Below is the syntax for declaring a method in C#:

Create a Method

In C#, a method declaration encompasses the following essential components:

  • Modifier: The modifier determines the accessibility of the method, indicating where it can be accessed within the application. Common access modifiers include public, protected, and private, which control the visibility and usage of the method.
  • Method Name: This is the distinctive identifier given to the method, enabling users to call or reference it. For instance, a method designed to retrieve a person's name might be named GetName().
  • Return Type: The return type specifies the data type of the value that the method will produce upon completion. It could be any valid C# data type, such as int, double, or a custom class. If the method doesn't produce a result, the return type is declared as void.
  • Body of the Methods in C#: The method body contains the sequence of code statements that the method will execute when invoked. These statements accomplish specific tasks or calculations and are enclosed within curly braces {}.
  • Parameter List: The parameter list consists of input parameters enclosed within parentheses (). Each parameter is defined by its data type and a name, such as (int x, double y). If a method doesn't require any parameters, empty parentheses are used, like ().

Call a Method

Method invocation, also known as method calling, is the act of triggering the execution of a defined method in a C# program. This is done when the user intends to utilize the functionality provided by that method. When a method in C# is invoked, it performs a specific set of actions based on its implementation and may produce a result or side effects. A method can be invoked by providing the necessary input arguments that it expects. The method executes its statements in the order they are defined.

Method invocation involves the following steps:

  • Call: The user initiates the execution of a method by calling it and providing any required input values (arguments).
  • Execution: The method's statements are executed in sequence, performing the actions specified by the method's implementation.
  • Result or Exception: The methods in C# either complete their statements, reach a return statement to provide a result or throw an exception due to an error.
  • Return: Once the method execution is complete, the control returns to the point where the method was called, and any result or exception information is processed as necessary.

This process allows developers to create modular and reusable code by encapsulating specific functionalities within methods that can be easily invoked when needed.

Example: In the code below, a method named Add() is called.

Output:

Recursive Method Call

A recursive method in C# is a method that calls itself to solve a problem. Recursive methods in C# are often used to break down complex problems into simpler sub-problems, making the code more elegant and easier to understand. However, it's essential to have a base case that defines when the recursion should stop to prevent infinite recursion.

Here's an example of a recursive methods in C# that calculates the factorial of a given number:

Output:

In this example, the Factorial method calculates the factorial of a non-negative integer n. The base condition occurs when n equals 0 or 1, in which case the method returns 1. For any other value of n, the method calls itself with a reduced value of n and multiplies the current n with the result of the recursive call.

Method Parameters

In certain scenarios, users may need to run a method, yet that method might necessitate specific input values to effectively carry out its tasks and achieve completion. These input values, commonly referred to as parameters in the realm of computer languages, serve as essential information for the method's proper functioning.

These parameters can assume various data types like int, long, float, double, or char, contingent upon the particular needs of the user. The categorization of methods in C# can be accomplished based on both their return types and the types of input parameters they accept.

Example 1: Program Without Parameters & Without Return Type

Output:

Example 2: Program Without Parameters & With Return Value Type

Output:

Example 3: Program With Parameters & Without Return Value Type

Output:

Example 4: Program With Parameters & With Return Value Type

Output:

Advantages of Methods

Here are some key advantages of using methods in C#:

  • Modularization and Code Organization: Methods in C# enable you to dissect intricate tasks into more compact, manageable segments of code. This makes the overall codebase more organized and easier to understand.
  • Reusability: Once you've defined a method, you can reuse it multiple times across your program or even in different projects. This saves you time and effort by preventing the need to rewrite the same code logic.
  • Readability and Maintainability: Breaking code into smaller methods in C# with meaningful names makes it easier to read and understand. This aids both you and other developers in maintaining and updating the codebase over time.
  • Parameterization: Methods in C# can accept input parameters, allowing you to make them adaptable to various scenarios. This flexibility helps in creating more versatile and adaptable code.
  • Encapsulation: Methods in C# help in encapsulating specific functionality, which means you can isolate specific tasks or operations within their scope. This promotes the principle of encapsulation in object-oriented programming.
  • Abstraction: Methods in C# allow you to abstract away the details of how a task is performed. This means you can call a method to achieve a specific task without needing to know the intricate implementation details.
  • Testing: Well-defined methods in c# make unit testing easier. You can isolate individual pieces of functionality and test them independently, which leads to more effective and efficient testing.

Conclusion

  • Methods in C# enable breaking down complex tasks into manageable units, making code more readable and maintainable.
  • Methods in C# are the cornerstone of structured programming, providing a systematic way to encapsulate logic, improve code reusability, and enhance code organization.
  • Calling methods execute their defined logic, and they can return values or modify data as required.
  • Methods foster abstraction, enabling you to focus on what a piece of code does rather than how it does it. By encapsulating complex logic within methods, you create a higher-level representation of functionality.
  • Methods are invaluable when it comes to testing and debugging. By isolating specific functionality within methods, you create units that can be tested individually.