DEV Community

mohamed Tayel
mohamed Tayel

Posted on

Mastering C# Fundamentals: Methods

Meta Description:
Learn how to create and use methods in C# to improve code reusability, maintainability, and readability. This guide covers the basics of methods, including parameters, return types, and real-world examples like shopping cart price calculation. Perfect for developers looking to master efficient coding practices in C#.

When writing code, our programs often follow a sequential flow—a set of instructions executed one after the other. This works for simple tasks, but when you need to repeat the same logic at different points in your program, it becomes inefficient. Imagine you’ve written code to calculate an employee's wage or the total price of items in a shopping cart. Duplicating the same logic is not a good approach. If the calculation changes, you’d need to update it in multiple places, leading to potential errors and unnecessary complexity.

Instead, you can use methods. By placing repetitive code inside a method, you write the logic once and reuse it whenever needed. This reduces redundancy and makes the code cleaner, more maintainable, and easier to understand.

What are Methods?

In C#, methods are blocks of code that perform specific tasks. They provide a way to group code that you might want to reuse or call multiple times throughout your application. Methods can contain just a single line of code or several statements. By encapsulating logic inside a method, you improve code organization and reusability.

Key components of a method:

  • Name: A unique identifier that you use to call the method.
  • Parameters: Inputs that the method requires to perform its task.
  • Return type: Specifies the type of value the method returns. If the method does not return any value, you use the void return type.

Why Use Methods?

  1. Reusability: Methods allow you to write code once and use it multiple times.
  2. Maintainability: When logic changes, you only need to update the method, not every place where the logic is used.
  3. Readability: Methods help break down complex tasks into smaller, manageable pieces, making your code easier to follow.

Structure of a Method

A typical method in C# looks like this:

public int AddTwoNumbers(int a, int b)
{
    return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Let’s break it down:

  • public: The access modifier defines the visibility of the method. It controls where the method can be called from.
  • int: The return type specifies that the method returns an integer value.
  • AddTwoNumbers: The method name that uniquely identifies the method.
  • int a, int b: These are the parameters (or inputs) the method takes.
  • return a + b;: This is the return statement that sends the result back to the calling code.

Calling a Method

Once a method is defined, you can invoke or call it from anywhere in your program. Here’s how you would call the AddTwoNumbers method:

int result = AddTwoNumbers(10, 20);
Console.WriteLine(result);  // Output: 30
Enter fullscreen mode Exit fullscreen mode

In this example, the values 10 and 20 are passed to the method as arguments, and the method returns their sum, 30, which is then printed to the console.

Return Types

Methods can return different types of values, such as integers, strings, or boolean values. If a method doesn’t need to return any value, you use the void return type. For example:

public void DisplaySum(int a, int b)
{
    Console.WriteLine(a + b);
}
Enter fullscreen mode Exit fullscreen mode

Since this method only prints the sum and doesn’t return anything, we use void. Here’s how to call it:

DisplaySum(10, 20);  // Output: 30
Enter fullscreen mode Exit fullscreen mode

Return Statement

The return keyword is used to send a value back to the caller and stop the method's execution. Here’s an example:

public int MultiplyTwoNumbers(int a, int b)
{
    return a * b;
}
Enter fullscreen mode Exit fullscreen mode

When the return statement is reached, the method stops, and the result is sent back to the caller.

Multiple Execution Paths

Sometimes, a method contains multiple paths of execution, such as when using if statements. For instance:

public int CompareNumbers(int a, int b)
{
    if (a > b)
        return a;
    else
        return b;
}
Enter fullscreen mode Exit fullscreen mode

This method returns the larger of the two numbers. You must ensure that all possible execution paths return a value, or the compiler will throw an error.


Let's Implement This in Visual Studio

Now that we've covered the basics, it's time to head to Visual Studio to see how methods work in action. We’ll use the concept of methods to calculate the total price of items in a shopping cart, applying a discount if the number of items exceeds a certain threshold.

Step-by-Step Example: Shopping Cart Price Calculation

Let’s walk through the steps of writing a method called CalculateTotalPrice that takes two parameters: the price per item and the number of items. If the quantity exceeds 5, a 10% discount is applied.

Here’s how you define the method in your Program.cs file:

public static void CalculateTotalPrice(decimal pricePerItem, int quantity)
{
    decimal totalPrice = pricePerItem * quantity;

    if (quantity > 5)
    {
        totalPrice *= 0.9m; // Apply 10% discount
    }

    Console.WriteLine($"The total price is: {totalPrice}");
}
Enter fullscreen mode Exit fullscreen mode

Invoking the Method

You can invoke this method in your program like this:

decimal itemPrice = 20.50m;  // Price per item
int numberOfItems = 7;       // Quantity

CalculateTotalPrice(itemPrice, numberOfItems);
Enter fullscreen mode Exit fullscreen mode

In this case, the total price will include the 10% discount because the quantity exceeds 5.

Returning Values from Methods

Right now, the method prints the total price to the console. What if you want to use the total price elsewhere in your program? Let’s modify the method to return the total price instead:

public static decimal CalculateTotalPrice(decimal pricePerItem, int quantity)
{
    decimal totalPrice = pricePerItem * quantity;

    if (quantity > 5)
    {
        totalPrice *= 0.9m; // Apply 10% discount
    }

    return totalPrice;
}
Enter fullscreen mode Exit fullscreen mode

Now, you can store the result in a variable and use it later:

decimal totalPrice = CalculateTotalPrice(itemPrice, numberOfItems);
Console.WriteLine($"The total price is: {totalPrice}");
Enter fullscreen mode Exit fullscreen mode

Debugging and Stepping Through Code

Using Visual Studio’s debugger, you can step through your method and observe how values are passed and processed. Set breakpoints at method calls, then use F11 to step into the method or F10 to execute each line and inspect how the method behaves.

Adding Additional Logic

You can expand the logic of the method, such as adding an extra discount for orders exceeding $100:

public static decimal CalculateTotalPrice(decimal pricePerItem, int quantity)
{
    decimal totalPrice = pricePerItem * quantity;

    if (quantity > 5)
    {
        totalPrice *= 0.9m; // Apply 10% discount
    }

    if (totalPrice > 100)
    {
        totalPrice -= 5; // Apply extra $5 discount for large purchases
    }

    return totalPrice;
}
Enter fullscreen mode Exit fullscreen mode

This method now applies multiple discounts based on the conditions of the cart, illustrating how flexible and powerful methods can be.


Conclusion

Methods are essential for writing clean, reusable, and maintainable code in C#. By using methods, you encapsulate logic into manageable pieces, avoiding repetition and making your programs easier to understand and modify. Whether you're calculating the price of items in a shopping cart or performing complex business logic, methods provide an efficient way to organize your code.

Key Takeaways:

  • Methods allow you to encapsulate reusable code blocks.
  • They improve maintainability and readability.
  • Return types specify what value, if any, a method returns.
  • Parameters let you pass values into methods for more flexible logic.
  • Debugging in Visual Studio can help you better understand how your methods work.

By mastering methods, you will significantly improve your ability to write efficient and clean C# code. Now it’s time to implement your own methods in Visual Studio!

Top comments (0)