Download presentation
Presentation is loading. Please wait.
Published byMeredith Dean Modified over 6 years ago
1
COMP 170 – Introduction to Object Oriented Programming
<Name of Instructor> Department of Computer Science 1
2
Notes on C# Functions A C# function definition is like writing the instructions for a recipe in a cookbook – nothing happens until you look up the recipe in the cookbook and follow its instructions to make something When C# sees a function definition it simply stores it away until the function is called somewhere else in the program A C# function call is like you taking the cookbook down from a shelf and following the instructions for a particular recipe to make the dish You can also think of a C# function definition as defining a “miniature program” – that “program” can have inputs, usually includes statements that accomplish something, and can produce outputs Another way to think about a C# function is that it’s like someone sitting at a desk who performs some activities; the things in the person’s inbox are the function’s inputs, what he or she does are the function’s statements, and the things going to the person’s outbox are the function’s outputs
3
How Do I Define a C# Function?
A C# function definition starts with the special keyword static, followed by the type of its returned value, if any, the name of the function, and parentheses, possibly with comma-separated paired types and item names inside them, like this: static returnType FunctionName (0 or more items ) these are called parameters The lines immediately following this function header or “signature” line that are inside matching curly braces, { }, are part of the function definition – they are called the function body, and they say what the function will do when it’s called (but the definition is just saved away for now) A special return type of “void” means that the function does not return a value Function parameters are sometimes called formal parameters You use parameter names just like variable names inside the function body; you can also assign to and use local variables inside the function
4
How Do I Call a C# Function?
Once you have defined a function you call it in your program by writing its name, parentheses, and the same number of comma- separated items that are in the function definition parentheses: FunctionName (0 or more items) these are called arguments You do not write the static keyword, and you do not include the return type or the parameter types; however, the types of the function arguments in the call must match or be “compatible with” the types of the corresponding parameters Once the function finishes executing statements in the function body, program execution continues following the function call (execution “jumps into” the function, performs its statements, and “jumps back” to the point of the call) Function arguments are also called actual parameters When a function is called the values of the compatible arguments are copied into the function’s parameters, if any, from left to right A function argument is “compatible with” its corresponding parameter if it can be automatically converted into the required type; for example, an int argument value is compatible with a double parameter type because C# can automatically convert integer values into doubles
5
C# Function Example Defining and saving away a “SayHello” function: static void SayHello() // nothing in the parentheses { Console.WriteLine("Hello, world!"); } // note: a “void” return type means no returned value Calling the SayHello function: SayHello(); // also nothing in the parentheses This prints Hello, world! on the monitor because the function’s single Console.WriteLine() statement is executed (only) when the function is called; after that, execution continues after that call By convention, C# function names always start with a capital letter; following “words” that are part of the function name either start with another capital letter or are separated by underscores, _ The opening curly brace, {, is either written just to the right of the right parenthesis in the function header, or, as shown, below the header and lined up with its left edge. By convention, the lines of the function definition are indented consistently. However, C# does not pay attention to indentation or any other “white space”; it only uses the curly braces to delimit things!
6
Another C# Function Example
Defining and saving away a “SayHelloTo” function: static void SayHelloTo(string name) // one item in the parens { Console.WriteLine("Hello," + name); } // note that there is a space after the comma in "Hello," Calling the SayHelloTo function: string s = "Fred"; // or, string s = Console.ReadLine(); SayHelloTo(s); // same number of items, just one This prints Hello, Fred on the monitor The single parameter name is of type string, so the argument in a call to SayHelloTo must be “compatible with” type string When a function is called the values of each of the arguments in the call are assigned to the corresponding parameters, left to right In this case it’s as though the following assignment statement is the first line of the function: string name = "Fred"; Inside the function body all of the parameters can be used as though they were initialized variables of their defined types
7
A Third C# Function Example
Defining and saving away a “ReturnHello” function: static string ReturnHello() // the return type is now string { return "Hello, world!"; // returns a constant string value } Calling the ReturnHello function: string hw = ReturnHello(); // save the function output in hw Now the string variable hw refers to the string "Hello, world!" because the function’s returned value was assigned to hw A function that has a non-void return type must include at least one return statement A return statement consists of the word “return” followed by an expression that is compatible with the function’s return type, in this case string When you call a function that returns a value you should always use the value in some way: assign it to a variable, print it, or do something else with it … otherwise the returned value will be “lost”
8
C# Function Definitions
When you define a function you specify five things: The return type of the function, eg, void or string The name of the function, eg, SayHelloTo The inputs the function will receive from its caller, if any, specified as parameters (comma-separated typed names in its parentheses), eg, string name How the function works (what it does), specified by the statements inside the function definition { } What the function returns to its caller, if anything, specified by 0 or more return statements inside the function – its output to its caller The statements inside the function definition may define/assign values to function “local variables” or use the function’s parameters in some way If the function returns a value, each return statement in the function can return only a single value compatible with its return type
9
Calling a C# Function When you call a function you specify three things: The name of the function, eg, SayHelloTo The inputs the function will receive, if any, from its caller, specified as arguments (comma- separated items inside its parentheses), eg, "Fred" What to do with a value that the function returns Print the value Save the value in a variable by assigning to it Pass the value to another function Anything else … don’t ignore the value If a function returns a value you should always do something with the value Ignoring a returned value is almost always a logic error in your program If a function does not return a value (if its return type is void) then its call should be a stand-alone statement – don’t try to use its value! For example, Console.WriteLine() is a void function, so this statement will not compile: string s = Console.WriteLine("Hello, world!");
10
Another C# Function with Return
Defining a “HelloTo” function with a returned value: static string HelloTo(string name) { return "Hello, " + name; // return statement } Calling the HelloTo function and saving its output: string output = HelloTo("Fred"); // saved value This sets the variable output equal to "Hello, Fred", essentially “capturing” the function’s output
11
Function Requirements – 1
How to define a function based on its requirements: If the requirements say the function should ask for/obtain/get/receive input from the user, then it should contain one or more ReadLine() functions This is a typical way to use ReadLine(): Console.Write("Please enter your name: "); string name = Console.ReadLine(); If the requirements do not say this, then the function should not contain ReadLine() calls; in that case its only inputs come from its parameters! Typically a function either uses ReadLine() function calls to obtain input from the user or it gets its input(s) from its parameters Sometimes a function will do both – it will receive one or more parameters but it will also request input from the user If the function contains ReadLine() function calls, you may need to use int.Parse() or double.Parse() in order to convert the input to a number
12
Function Requirements – 2
How to define a function based on its requirements: If the requirements say the function should print or display output, then it should contain one or more Console.WriteLine() (or Console.Write()) function calls and probably no return statements If the requirements do not say this, the function should not contain Console.WriteLine() calls; in that case its outputs only go back to its caller via its return statements, if any! A typical Console.WriteLine() function call is: Console.WriteLine("The answer is" + answer); Typically a function will either print its output or return a value to its caller, but not both A function may do neither – it may not print anything and also not return a value to its caller If a function contains Console.WriteLine() function calls, you may want to use a format string with {0}, etc, in order to generate the correct output
13
More on Calling a C# Function
When you call a function with parameters … You specify the arguments to the function (items inside its calling parentheses, separated by commas, one item for each of the parameters) Essentially those arguments are assigned to the parameters in the same order they are listed A function's arguments (its inputs) can be any of: Literal values like 42, "Fred", or Variable names like x, varName, input_value, … Expressions like x/y, stringName + "Fred", etc Function or method calls like Console.ReadLine() Any of these must be compatible with their corresponding parameter types Literal values can be strings, ints, doubles, … Variable names are references to any type of C# value – they are replaced by their current values Expressions may be arithmetic operations, string concatenation, etc. – they are replaced by their calculated values Function or method calls used as arguments must return values of compatible types (you can’t use a void function call as a function argument)
14
Function Returned Values
When you call a function you may receive a value: If the function returns a value then you should use it in some way – print it, use it in an expression, assign it to a variable, etc. If the function does not return a value then its call should appear as a stand-alone statement; in that case the function is being called to produce what is known as a "side effect", like printing something The returned value from a non-void function might be a created or built-up string, a sum, a product, something the user typed, …
15
C# Function Examples – 1 How would you define a function called F that takes no parameters and prints a message? static void F() // function definition line { Console.WriteLine("a message"); // function body } // note: no return statements in this function How would you define a function called F2 that takes no parameters and returns a string with a message? static string F2() // function definition line { return "a message"; // returns a string } returnedString = F2(); // example of how to use F2
16
C# Function Examples – 2 How would you define a function called G that takes one string parameter and prints that parameter? static void G(string x) // the parameter name x is arbitrary { Console.WriteLine(x) // it could be param1, fred, … } // note: use the same name x in both places How would you define a function called G2 that takes one string parameter and returns that parameter? static string G2(string x) // again the name x is arbitrary { return x; // the returned value must be a string (x is!) }
17
C# Function Examples – 3 How would you define a function called H that takes two int parameters and prints their int sum? static void H(int a, int b) // names a and b are arbitrary { Console.WriteLine(a + b); // use a & b like variables } H(2,3); // a = 2; b = 3; int x = 2, y = 3; H(x, y); // exactly the same: a = x; b = y; How would you define a function called H2 that takes two int parameters and returns their int sum? static int H2(int a, int b) // int return type { return a + b; // no need to use parentheses for a + b } // however, return (a + b); also works
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.