C# Methods

A method in C# is an organized block of reusable code, which avoids repeating the tasks again and again. If you want to do a task repeatedly in a code, then just make a method, set the task in it, and call the multiple times whenever you need it. These are also called Functions.

We have discussed the following topics:

  • Create a Method
  • Call a Method
  • Method Parameters
  • Multiple Parameters
  • Recursion
  • Recursion Example
  • Create and call a Method

Create a Method

To create a method in C#, set the name of the function followed by parentheses. We have set the access specifier and return type as well. Let us see an example syntax:

The static keyword suggests the method belongs to the Studyopedia class. It is not an object of the Studyopedia class.

Call a Method

To call a method in C#, just write the method name as shown below. A method in C# gets executed when it is called:

Let us now see an example to create and call a Method in C#:

Output

Method Parameters

Set the parameters in a C# method after the name of the method. For example:

To call a function with a parameter, set the value of the variable while calling, for example:

Therefore, we have passed the rank with the value 2 while calling above.

Let us now see an example:

Output

Multiple Parameters

We can also set more than one parameter in a function in C#. For example:

To call a function with multiple parameters, set the value of the variable while calling, for example:

We have passed the following multiple parameters while calling above:

  • player: Amit
  • rank: 1
  • points: 90

Let us now see an example to implement multiple parameters for methods in C#:

Output

Recursion in C#

In C#, when a function calls itself, it is called Recursion. In another sense, with Recursion, a defined function can call itself. Recursion is a programming approach, which makes code efficient and reduces LOC.

The following figure demonstrates how recursion works when we calculate Factorial in C# with Recursion:

C# Recursion

Recursion Example

Let us now see how to find the factorial of a number in C# with Recursion:

Output


If you liked the tutorial, spread the word and share the link and our website Studyopedia with others.


For Videos, Join Our YouTube Channel: Join Now


C# Classes and Objects
C# Method Overloading
Studyopedia Editorial Staff
contact@studyopedia.com

We work to create programming tutorials for all.

No Comments

Post A Comment

Discover more from Studyopedia

Subscribe now to keep reading and get access to the full archive.

Continue reading