In C#, functions and methods are used to encapsulate code that performs a specific task. Here are some of the key concepts related to functions and methods in C#:
1. Functions vs. methods: In C#, a function is a standalone piece of code that performs a specific task and returns a value. A method, on the other hand, is a function that is associated with a class or an object. Methods can be used to manipulate the data of an object or to perform operations on that object.
2. Declaring functions: To declare a function in C#, you use the following syntax:
access_modifier return_type function_name(parameters) { // code to execute return value; }
For example:
public int Add(int x, int y) { int result = x + y; return result; }
This code declares a function named “Add” that takes two integer parameters and returns the sum of those parameters.
3. Calling functions: To call a function in C#, you use the following syntax:
return_value = function_name(arguments);
For example:
int sum = Add(2, 3);
This code calls the “Add” function with the arguments 2 and 3 and assigns the result to the variable “sum”.
4. Declaring methods: To declare a method in C#, you use the following syntax:
access_modifier return_type method_name(parameters) { // code to execute return value; }
For example:
public class Calculator { public int Add(int x, int y) { int result = x + y; return result; } }
This code declares a class named “Calculator” that contains a method named “Add” that takes two integer parameters and returns the sum of those parameters.
5. Calling methods: To call a method in C#, you create an instance of the class and use the following syntax:
Class_name object_name = new Class_name(); return_value = object_name.method_name(arguments);
For example:
Calculator myCalculator = new Calculator(); int sum = myCalculator.Add(2, 3);
This code creates an instance of the “Calculator” class named “myCalculator” and calls the “Add” method with the arguments 2 and 3.
Functions and methods are fundamental to writing reusable and modular C# code. By using functions and methods, you can encapsulate code that performs a specific task and use that code in different parts of your program.