Creating and Using Methods in C#

Tutorial 1 of 5

Creating and Using Methods in C

1. Introduction

In this tutorial, we will learn how to create and use methods in C#. We will define methods, invoke them, and understand their role in programming.

At the end of this tutorial, you should be able to:

  • Define and call methods in C#
  • Understand the importance of methods in programming

This tutorial assumes that you have a basic understanding of C# syntax.

2. Step-by-Step Guide

In C#, methods are blocks of code that perform specific tasks. They are defined inside a class or struct, and they are used to organize code into manageable pieces. A method can also return a value and take parameters.

How to Define a Method

A method is defined with the following syntax:

access_modifier return_type method_name( parameters )
{
   // method body
}

Here's a simple example:

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

In this example, public is the access modifier, int is the return type, Add is the method name, and (int a, int b) are the parameters.

How to Call a Method

Once a method is defined, it can be called from another method, constructor, or property. Here's an example:

int result = Add(5, 10);

In this example, Add method is being called with two arguments, 5 and 10. The result of the operation is stored in the result variable.

3. Code Examples

Example 1

class Program
{
    static void Main(string[] args)
    {
        int result = Add(5, 10);
        Console.WriteLine(result);  // Outputs: 15
    }

    static int Add(int a, int b)
    {
        return a + b;  // Returns the sum of a and b
    }
}

Example 2

class Program
{
    static void Main(string[] args)
    {
        SayHello("John");  // Outputs: Hello, John!
    }

    static void SayHello(string name)
    {
        Console.WriteLine("Hello, " + name + "!");
    }
}

4. Summary

In this tutorial, we've covered how to create and use methods in C#. We learned how to define a method, call it, and understand its purpose in programming.

Next, you might want to learn about more advanced topics related to methods, such as method overloading, optional parameters, and recursion.

5. Practice Exercises

Exercise 1

Write a method that takes two integers as parameters and returns their product.

Solution 1

static int Multiply(int a, int b)
{
    return a * b;
}

Exercise 2

Write a method that takes a string as a parameter and prints it to the console.

Solution 2

static void PrintMessage(string message)
{
    Console.WriteLine(message);
}

Exercise 3

Write a method that takes no parameters and returns a random number.

Solution 3

static int GenerateRandomNumber()
{
    Random random = new Random();
    return random.Next();
}

Remember to practice regularly to enhance your understanding of methods in C#.