Presentation is loading. Please wait.

Presentation is loading. Please wait.

Lecture 3 Functions Simple functions

Similar presentations


Presentation on theme: "Lecture 3 Functions Simple functions"— Presentation transcript:

1 Lecture 3 Functions Simple functions
Transfering data through functions Scope of variables Using command-line arguments with the Main() function Supplying functions as members of struct types Function overloading Delegates

2 Definition of a Function
Functions in C# are a means of providing blocks of code that can be executed at any point in an application. You could have a function that calculates the maximum value in an array. You can use the function from any point in your code, and use the same lines of code in each case. Because you only need to supply this code once, any changes you make to it will affect this calculation wherever it is used. The function can be thought of as containing reusable code.

3 Example: A Simple Function

4 Function Return Values
The simplest way to exchange data with a function is to use a return value. Functions that have return values evaluate to that value exactly the same way that variables evaluate to the values they contain when you use them in expressions. Just like variables, return values have a type. For example, you might have a function called GetVal( ) that returns a double value, which you could use in a mathematical expression: double myVal; double multiplier = 5.3; myVal = GetVal() * multiplier;

5 Function Parameters Values can be passed through a function's argument list are called parameters. When a function is to accept parameters, you must specify the following: A list of the parameters accepted by the function in its definition, along with the types of those parameters A matching list of parameters in each function call

6 Example: Using Parameter

7 Reference and Value Parameters
All the functions defined so far in this chapter have had value parameters. That is, when you have used parameters, you have passed a value into a variable used by the function. Any changes made to this variable in the function have no effect on the parameter specified in the function call. Alternatively you can pass the parameter by reference, which means that the function will work with exactly the same variable as the one used in the function call, not just a variable that has the same value. Any changes made to this variable will, therefore, be reflected in the value of the variable used as a parameter. To do this, you simply use the ref keyword to specify the parameter.

8 Example: Pass by Reference
static void ShowDouble(ref int val) { val *= 2; Console.WriteLine("val doubled = {0}", val); } int myNumber = 5; Console.WriteLine("myNumber = {0}", myNumber); ShowDouble(ref myNumber);

9 Out Parameters In addition to passing values by reference, you can specify that a given parameter is an out parameter by using the out keyword, which is used in the same way as the ref keyword. The value of the parameter at the end of the function execution is returned to the variable used in the function call. Whereas it is illegal to use an unassigned variable as a ref parameter, you can use an unassigned variable as an out parameter. An out parameter must be treated as an unassigned value by the function that uses it. This means that while it is permissible in calling code to use an assigned variable as an out parameter, the value stored in this variable is lost when the function executes.

10 Example: Use of out Parameter
static int MaxValue(int[] intArray, out int maxIndex) { int maxVal = intArray[0]; maxIndex = 0; for (int i = 1; i < intArray.Length; i++) if (intArray[i] > maxVal) maxVal = intArray[i]; maxIndex = i; } return maxVal; . . . int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 }; int maxIndex; Console.WriteLine("The maximum value in myArray is {0}", MaxValue(myArray, out maxIndex)); Console.WriteLine("1st occurrence is at element {0}", maxIndex + 1);

11 Variable Scope The scope of a variable encompasses the code blocks in which it is defined and any directly nested code blocks. This also applies to other code blocks, such as those in branching and looping structures. Consider the following code: int i; for (i = 0; i < 10; i++) { string text = "Line " + Convert.ToString(i); Console.WriteLine("{0}", text); } Console.WriteLine("Last text output in loop: {0}", text); Here, the string variable text is local to the for loop. This code won’t compile because the call to Console.WriteLine( ) that occurs outside of this loop attempts to use the variable text, which is out of scope outside of the loop.

12 Variable Scope (cont.) The previous code segment can be modified in the following way: int i; string text = ""; for (i = 0; i < 10; i++) { text = "Line " + Convert.ToString(i); Console.WriteLine("{0}", text); } Console.WriteLine("Last text output in loop: {0}", text); This time text is initialized outside of the loop, and you have access to its value.

13 THE MAIN( ) FUNCTION The Main( ) function is the entry point for a C# application and that execution of this function encompasses the execution of the application. That is, when execution is initiated, the Main( ) function executes, and when the Main( ) function finishes, execution ends. The Main() function can return either void or int, and can optionally include a string[] args parameter, so you can use any of the following versions: static void Main() static void Main(string[] args) static int Main() static int Main(string[] args) The third and fourth versions return an int value, which can be used to signify how the application terminates, and often is used as an indication of an error. In general, returning a value of 0 reflects normal termination (that is, the application has completed and can terminate safely). The optional args parameter of Main( ) provides you with a way to obtain information from outside the application, specified at runtime. This information takes the form of command-line parameters.

14 Struct Functions Consider the use of a struct function to simplify a common string manipulation task: struct CustomerName { public string firstName, lastName; public string Name() return firstName + " " + lastName; } This looks much like any other function you’ve seen in this chapter, except that you haven’t used the static modifier. The reasons for this will become clear later in the book; for now, it is enough to know that this keyword isn’t required for struct functions. You can use this function as follows: CustomerName myCustomer; myCustomer.firstName = "John"; myCustomer.lastName = "Franklin"; Console.WriteLine(myCustomer.Name());

15 MaxValue( ) for an integer Array
class Program { static int MaxValue(int[] intArray) int maxVal = intArray[0]; for (int i = 1; i < intArray.Length; i++) if (intArray[i] > maxVal) maxVal = intArray[i]; } return maxVal; static void Main(string[] args) int[] myArray = { 1, 8, 3, 6, 2, 5, 9, 3, 0, 2 }; int maxVal = MaxValue(myArray); Console.WriteLine("The max value in myArray is {0}", maxVal); Console.ReadKey();

16 Overloaded Function for MaxValue( )
static double MaxValue(double[] doubleArray) { double maxVal = doubleArray[0]; for (int i = 1; i < doubleArray.Length; i++) if (doubleArray[i] > maxVal) maxVal = doubleArray[i]; } return maxVal; Both the integer and double versions of MaxValue( ) function can be defined without ambiguity because their differences are used to determine which function is appropriate at compile time.

17 DELEGATES A delegate is a type that enables you to store references to functions. The most important purpose of delegates will become clear later, but it is useful to briefly consider them here. Delegates are declared much like functions, but with no function body and using the delegate keyword. The delegate declaration specifies a return type and parameter list. delegate double ProcessDelegate(double param1, double param2); static double Multiply(double param1, double param2) { return param1 * param2; } static double Divide(double param1, double param2) return param1 / param2;

18 Use of Delegate static void Main(string[] args) {
ProcessDelegate process; Console.WriteLine("Enter 2 numbers separated with a comma:"); string input = Console.ReadLine(); int commaPos = input.IndexOf(’,’); double param1 = Convert.ToDouble(input.Substring(0, commaPos)); double param2 = Convert.ToDouble(input.Substring(commaPos + 1, input.Length - commaPos - 1)); Console.WriteLine("Enter M to multiply or D to divide:"); input = Console.ReadLine(); if (input == "M") process = new ProcessDelegate(Multiply); else process = new ProcessDelegate(Divide); Console.WriteLine("Result: {0}", process(param1, param2)); Console.ReadKey(); }


Download ppt "Lecture 3 Functions Simple functions"

Similar presentations


Ads by Google