C# Function

Function

In C#, a function is a block of code that performs a specific task or action. Functions in C# are used to organize code into reusable modules, which helps in reducing redundancy and improving code maintainability.

A function in C# typically has a return type and a name and may accept input parameters.

Here's a basic syntax:

< access modifier > static <return type > < function name > (< parameters >)
        {
            // Function body
        }

Access Modifiers: Functions in C# can have access modifiers like public, private, protected, etc., which control the accessibility of the function from other parts of the program.

Static Method: When used with methods (public static void MyMethod()), it means that the method belongs to the class itself rather than to instances of the class. Static methods can be called without creating an instance of the class.

Return Type: Functions may return a value of a specified data type using the return statement. If a function doesn’t return anything, its return type is specified as void. Commonly we used void as the return type.

Parameters:  Parameters are used to pass data to the function for processing. Functions can accept zero or more input parameters.

Scenario: Create a program 1. Create a custom function with the name Message() which prints Hello World! in the console 2. Call that custom function in the main method

Example of 1: In the below image as you can see we define static in the custom function that’s why the system allows to select message function in the main method

In the below image as you can see we if we do not define static in the custom function that’s why the system does not allows to select message function in the main method

Example of 2: In the below image as you can see we can’t call the custom function Message directly in the main method which doesn’t contain the static keyword.

In the below image as you can see we have to create an instance of the class like  (Program call = new Program(); )   and call that function like ( call.Message(); )so the function will be called and output will be  Hello, World! In console.

Function with Parameter & Return type

Scenario: Create a custom function with parameter and return type

1. create a custom function that takes a parameter as input, addition of that input, subtracts that addition value with 20, and shows the result in the console

2. call a custom function in the main method

Scenerio1 Explanation:

using System;

Includes the System namespace for basic functionalities like Console.

class Program

Defines a class named Program.

public static void operation(int num1, int num2)

Declares a method named operation that takes two integers as parameters.

int add = num1 + num2;

Adds num1 and num2 and stores the result in the variable add.

int subtract = 20 – add;

Subtracts the value of the add variable from 20 and stores the result in the variable subtract.

Console.WriteLine(subtract);

Prints the value of subtract to the console.

public static void Main()

Declares the main method, which is the entry point of the program.

operation(4, 5);

Calls the operation method with passing 4 and 5 as arguments.

Scenerio2 Explanation:

using System;

 Includes the System namespace for basic functionalities like Console.

class Program

Defines a class named Program.

public static int Addition(int num1, int num2)

Declares a method named Addition that takes two integers as parameters and returns an integer Value.

int add = num1 + num2;

Adds num1 and num2 and stores the result in the variable add.

return add;

Returns the value of add to the Addition function.

public static void Main()

Declares the main method, which is the entry point of the program.

int sum = Addition(4, 5);

Subtracts the value of sum from 20 and stores the result in the variable subtraction.

Console.WriteLine(subtraction);

Prints the value of subtraction to the console.

Course Video

Course Video In English
Task:

1. Calculate Factorial:
Create a function CalculateFactorial that takes an integer and returns its factorial.
Use a for loop inside the function.
Use an if-else statement to handle negative inputs by returning -1.

2. Check Prime:
Create a function IsPrime that takes an integer and returns true if it’s a prime number and false otherwise.
Use a for loop and an if statement to check for primality.

3. Sum of Even Numbers:
Create a function SumOfEvenNumbers that takes two integers as the range and returns the sum of all even numbers in that range.
Use a for loop and an if statement inside the function.
Use a continue statement to skip odd numbers.

4. Guessing Game:
Create a function PlayGuessingGame that generates a random number and prompts the user to guess it.
Use a do-while loop, if-else statements, and a break statement to handle the guessing logic.

5. Temperature Conversion:
Create a function ConvertCelsiusToFahrenheit that takes a double representing Celsius and returns the equivalent Fahrenheit.
Create a function PrintTemperatureCategory that takes a temperature in Fahrenheit and uses a switch statement to print “Cold”, “Warm”, or “Hot”.

6. Menu Display:
Create a function DisplayMenu that prints a menu and returns the user’s choice.
Use a while loop to keep displaying the menu until the user chooses to exit.
Use a switch statement to handle menu options.

7. Fibonacci Sequence:
Create a function PrintFibonacciSequence that takes an integer n and prints the first n numbers of the Fibonacci sequence.
Use a for loop and an if statement to handle the sequence generation.
Use a break statement if the sequence exceeds a certain number.

Frequently Asked Questions

Still have a question?

Let's talk

A function in C# is a block of code designed to perform a specific task. Functions allow developers to reuse code, making programs more modular and maintainable.

C# supports various types of functions, including void functions (no return value), return-type functions (e.g., int, string), static functions, and overloaded functions.

A void function does not return any value, whereas return-type functions return a specific data type such as int, string, or a custom object.

Parameters can be passed in three ways: by value, by reference (ref), or as output (out).

Optional parameters allow you to define default values for function arguments, so they can be omitted during function calls.

Both ref and out are used to pass arguments by reference. However, ref requires the variable to be initialized before being passed, while out does not.

Yes, a function in C# can return multiple values using out parameters or by returning a tuple.

A recursive function is a function that calls itself. It is commonly used to solve problems like factorial calculation or tree traversal.

The params keyword in C# allows a function to accept a variable number of arguments, making it more flexible for use cases like sum calculations or logging.

In C#, you can pass a function as a parameter using delegates or lambda expressions. This allows you to pass a function that matches a delegate signature to another method.

Example of passing a function as a parameter using a delegate:
public delegate void DisplayMessage(string message);

void PrintMessage(string message) {

    Console.WriteLine(message);

}

void ExecuteFunction(DisplayMessage messageFunction) {

    messageFunction(“Hello, World!”);

}

ExecuteFunction(PrintMessage);  // Passing function as a parameter

To pass a function with parameters, you need to define a delegate that matches the function’s signature. Then you can pass the function name as an argument.
Example:

public delegate void PrintDetails(string name, int age);

void ShowDetails(string name, int age) {

    Console.WriteLine(“Name: ” + name + “, Age: ” + age);

}

void CallFunction(PrintDetails printFunction) {

    printFunction(“John”, 30);

}

CallFunction(ShowDetails);  // Passing function with parameters

Functions without arguments can also be passed as parameters, but the delegate type should not accept any parameters. Here’s an example:

public delegate void SimpleFunction();

void DisplayMessage() {

    Console.WriteLine(“Hello from function without arguments!”);

}

void CallFunction(SimpleFunction func) {

    func();

}

CallFunction(DisplayMessage);  // Passing function without parameters