05_Methods.pdf
Document Details
Uploaded by Deleted User
Full Transcript
Shoolini University Yogananda School of AI, Computing & Data Science C# Programming(CSU1531) Methods Outline 9/12/2024 C# - Methods A method is a group of statements that together perform a task. Every C# program has at le...
Shoolini University Yogananda School of AI, Computing & Data Science C# Programming(CSU1531) Methods Outline 9/12/2024 C# - Methods A method is a group of statements that together perform a task. Every C# program has at least one class with a method named Main. To use a method, you - Define the method need to − - Call the method Defining Methods in C# When you define a method, you basically declare the elements of its structure. The syntax for defining a method in C# is as follows − (Parameter List) { // Method Body } Cont.… Following are the various elements of a method − Access Specifier This determines the visibility of a variable or a method from another class. Return type A method may return a value. The return type is the data type of the value the method returns. If the method is not returning any values, then the return type is void. Method name Method name is a unique identifier and it is case sensitive. It cannot be same as any other identifier declared in the class. Parameter list Enclosed between parentheses, the parameters are used to pass and receive data from a method. The parameter list refers to the type, order, and number of the parameters of a method. Parameters are optional; that is, a method may contain no parameters. Method body This contains the set of instructions needed to complete the required activity. Example static void MyMethod() { Console.WriteLine("I just got executed!"); } static void Main(string[] args) { MyMethod(); } // Outputs "I just got executed!" Different Parts of a Method/Function Example using System; static void Main(string[] args) { namespace CalculatorApplication { int a = 100; class MyClass { int b = 200; public int FindMax(int n1, int n2) int ret; { MyClass n = new MyClass(); int result; ret = n.FindMax(a, b); if (n1 > n2) Console.WriteLine("Max is : result = n1; {0}", ret ); else Console.ReadLine(); result = n2; } return result; } } } Types of Methods Built-In Methods: User-Defined Methods Which are already defined in the Defined by the developer or framework and available to be programmer explicitly. used by the developer or It reduces the complexity of a big programmer. program and optimizes the code Example: (Discussed in this ppt. so far) WriteLIne function to print the output on the console window and built-in Sqrt function to get the square root of a given number. Parameters of a method Here we are passing two values, x, and y, to the Add function, which takes two parameters (a and b). The parameters (x and y) that we are passing to the Add function are called Actual Parameters. The parameters (a and b) which are taken by the Add method are called Formal Parameters. When we call the Add method, the values of actual parameters are copied to the formal parameters. So, the x value, i.e., 10, is copied to a, and the y value, i.e., 15, is copied to b. Types of User-Defined Functions in C# Example: Methods with No using System; Argument and No namespace FunctionDemo { Return Type: class Program { static void Main(string[] args) When a method has no { arguments, it does not Sum(); receive any data from the Console.ReadKey(); calling method. Similarly, when it does not return a } value, the calling function static void Sum() does not receive any data { from the called method. int x = 10; int y = 20; int sum = x + y; Console.WriteLine($"Sum of {x} and {y} is {sum}"); } } } Methods with no Example: using System; Argument and with namespace FunctionDemo { Return Type class Program { static void Main(string[] args) When a method has no arguments, it receives no data from the calling { method but returns a value. int Result=Sum(); Console.WriteLine($"Sum is {Result}"); Console.ReadKey(); } static int Sum() { int x = 10; int y = 20; int sum = x + y; return sum; } } } Example: Methods with using System; namespace FunctionDemo Argument and no { Return Type class Program { static void Main(string[] args) { When a method has arguments, it int x = 10, y = 20; receives data from the calling Sum(x, y); method but does not return any value. Console.ReadKey(); } static void Sum(int x, int y) { int sum = x + y; Console.WriteLine($"Sum is {sum}"); } } } Example: Methods with using System; namespace FunctionDemo Argument and with { class Program Return Type { static void Main(string[] args) { When a method has arguments, it receives data from the calling method int x = 10, y = 20; and does return some value. int Result = Sum(x, y); Console.WriteLine($"Sum is {Result}"); Console.ReadKey(); } static int Sum(int x, int y) { int sum = x + y; return sum; } } } Call By Value and Call By Reference in C# Example: Call By Value using System; public class Example { In Call by Value, a copy of the public static void Main(string[] args) { actual value is passed to the int number = 10; method. Console.WriteLine("Before Call by Value: " + number); // Output: 10 The method works with this copy, so any changes made inside the method do not affect the original // Call by Value value. ModifyValue(number); This is the default way of passing parameters in C#. Console.WriteLine("After Call by Value: " + number); // Output: 10 (No change) } In this example, When we change num to 20, it only changes the static void ModifyValue(int num) { copy, not the original number. Output: number remains 10 outside num = 20; // This change does not affect the original value the method because the original value wasn’t modified. } } Call by Example: using System; Reference public class Example { In Call by Reference, public static void Main(string[] args) { a reference (or int number = 10; memory address) of Console.WriteLine("Before Call by Reference: " + number); the variable is passed // Output: 10 to the method. This allows the method to // Call by Reference work with the original value, so any changes ModifyValue(ref number); made inside the method do affect the Console.WriteLine("After Call by Reference: " + number); original variable. // Output: 20 (Changed) } In this example, the ref keyword is used to pass the variable static void ModifyValue(ref int num) { number by reference. num = 20; // This change affects the original value When num is changed } to 20, the original } number is also changed. Example: Recursion using System; public class RecursionExample { public static void Main(string[] args) { Recursion is a // Calculate the factorial of 5 programming technique int number = 5; where a method calls int result = Factorial(number); itself to solve a smaller instance of the same Console.WriteLine("Factorial of " + number + " is: " + result); problem. } It breaks down a // Recursive method to calculate factorial problem into simpler static int Factorial(int n) { sub-problems until it if (n == 1) { reaches a base case (a // Base case: when n is 1, return 1 condition where the recursion stops). return 1; } else { // Recursive case: n * factorial of (n-1) return n * Factorial(n - 1); } } } Scope of a Variable The scope means the lifetime of that variable. It means the variable can only be accessed or visible within its scope. The scope of variables can be defined with their declaration, and variables are declared mainly in two ways: Global Variable: Outside of all the functions Local Variable: Within a function block Example Global Variable class Program { static int globalVar = 20; // Global variable Global variables are static void Main(string[] args) { those variables which are declared outside of Console.WriteLine("Initial value: " + globalVar); all the functions or // Output: 20 block and can be ChangeValue(); // Modifying globalVar accessed globally in a Console.WriteLine("After change: " + globalVar); program. // Output: 50 Once we declare a } global variable, its value can be varied as used with different static void ChangeValue() { functions. globalVar = 50; // Changes the value stored in memory } } Example Local using System; class StudentDetails { Variable // Method public void StudentAge() { Variables that are declared // local variable age within or inside a block or method or constructor are known int age = 0; as Local variables. age = age + 10; These variables are created when Console.WriteLine("Student age is : " + age); the block is entered or the function is called and destroyed } after exiting from the block or // Main Method when the call returns from the function. public static void Main(String[] args) These variables can only be { accessed within the function in // Creating object which they are declared. StudentDetails obj = new StudentDetails(); // calling the function obj.StudentAge(); } } Thank You Any Questions ? 23