Busy. Please wait.
Log in with Clever

show password
Forgot Password?

Don't have an account?  Sign up 
Sign up using Clever

Username is available taken
show password

Make sure to remember your password. If you forget it there is no way for StudyStack to send you a reset link. You would need to create a new account.
Your email address is only used to allow you to reset your password. See our Privacy Policy and Terms of Service.

Already a StudyStack user? Log In

Reset Password
Enter the associated with your account, and we'll email you a link to reset your password.
Didn't know it?
click below
Knew it?
click below
Don't Know
Remaining cards (0)
Embed Code - If you would like this activity on your web page, copy the script below and paste it into your web page.

  Normal Size     Small Size show me how

Chapter 7

Methods: A Deeper Look

Divide and Conquer Technique Developing and maintaining a large app by constructing from small, simple pieces
Method Overloading When many of the classes you use or create have moore than one method of the same name. Is used to implement methods that perform similar tasks but with different types and/or different numbers of arguments
Methods(Functions, Procedures) Allow you to modularize an app by separating its tasks into self-contained units. The actual statements in the method bodies are written only once, can be reused from several locations in an app and are hidden from other methods
Software Reusability Existing methods can be used as building blocks to create new apps. This is one motivation for modularizing apps with methods. Every method should be limited to performing a single, well-defined task, with name expressing task effectively
Client Code Any code that calls a method.
Client of the Method Any statement that calls the object's method from outside the object
Declaring a Static Method To declare a static method, place the keyword static before the return type in the method's declaration.
Calling a Static Method You call any static method by specifying the name of the class in which the method is declared, followed by the member access(.) operator and the method name. Ex: ClassName.MethodName(arguments)
1. Math Class Methods 1. Method[Abs(x)]..Description[absolute value of x]..Example[Abs(-23.7) is 23.7]... 2. Method[Ceiling(x)]..Description[rounds x to the smallest integer not less than x]..Example[Ceiling(-9.8) is -9.0]...
2. Math Class Methods 3. Method[Cos(x)]..Description[trigonometric cosine of x(in radians)]..Example[Cos(0.0) is 1.0]... 4. Method[Exp(x)]..Description[exponential method(e^x)]..Example[Exp(1.0) is 2.71828]
3. Math Class Methods 5. Method[Floor(x)]..Description[rounds x to the largest integer not greater than x]..Example[Floor(-9.8) is -10.0]... 6. Method[Log(x)]..Description[natural logarithm of x(base e, ln)]..Example[Log(Math.E is 1.0)]
4. Math Class Methods 7. Method[Max(x, y)]..Description[larger value of x and y]..Example[Max(2.3, 12.7) is 12.7]... 8. Method[Min(x, y)]..Description[smaller value of x and y]..Example[Min(2.3, 12.7) is 2.3]...
5. Math Class Methods 9. Method[Pow(x, y)]..Description[x raised to the power of y]..Example[Pow(2.0, 7.0) is 128.0]... 10. Method[Sin(x)]..Description[trigonometric sine of x(kn radians)]..Example[Sin(0.0) is 0.0]...
6. Math Class Methods 11. Method[Sqrt(x)]..Description[square root of x]..Example[Sqrt(900.0) is 30.0]... 12. Method[Tan(x)]..Description[trigonometric tangent of x(in radians)]..Example[Tan(0.0) is 0.0]
Math Class Constants PI and E Two static double constants that represent commonly used mathematical values are Math.PI and Math.E. The constant Math.PI(3.141592...) is the ratio of a circle's circumference to its diameter. Math.E(2.71828...) is the base value for natural logarithms
Constant Declared with the keyword const and its value cannot be changed after the constant is declared. Both PI and E are declared const.
Instance Variables When each object of a class maintains its own copy of an attribute, the variable that represents the attribute is known as an instance variable - each object(instance) of the class has a separate instance of the variables
Static Variables The variables for which each object of a class odes not have a separate instance of. When objects of a class containing static variables are created, all the objects of that class share one copy of the class's static variables
Fields of a Class The static and instance variables of a class
Implicitly Static Constants Every constant declared in a class, but not inside a method of the class is implicitly static, so it's a syntax error to declare such a constant with the keyword static explicity
Why Is Method Main static? During app startup, when no objects have been created, the main method must be called to begin program execution. Main is sometimes called the app's entry point. Main is often declared with the following header: public static void Main(string args[])
1. Executing an App from the Command Line When you execute your app from the command line, you type the app name: AppName argument1 argument2.
2. Executing an App from the Command Line In the preceeding command, argument1 and argument2 are command line arguments to the app that specify a list of strings(separated by spaces) the execution environment will pass to the Main method of your app.
Additional Comments about Method Main You can place a Main method in every class you declare. If you declare more than one Main method among the classes of your project, you'll need to indicate to the IDE which one you would like to be the app's entry point
Indicating App's Entry Point to the IDE You can do this by selecting PROJECT>[ProjectName] Properties...(where [ProjectName] is the name of your project). and selecting the class containing the Main method that should be the entry point from the Startup object list box
Data Structures To understand how C# performs method calls, we first need to consider a data structure - a collection of related data items - known as a stack.
1. Stack You can think of a stack as analogous to a pile of dishes. When a dish is placed on the pile, it's normally placed at the top(referred to as pushing the dish onto the stack).
2. Stack Similarly, when a dish is removed from the pile, it's always removed from the top(referred to as popping the dish off the stack). Stacks are known as last-in, first-out(LIFO) data structures
Last-In, First-Out Data Structures A data structure in which the last item pushed(inserted) on the stack is the first item popped off(removed from) the stack.
1. Program Execution Stack When an app calls a method, the called method must know how to return to its caller, so the return address of the calling method is pushed onto the program-execution stack(method-call stack).
2. Program Execution Stack If a series of method calls occurs, the successive return addresses are pushed onto the stack in the last-in, first-out order so that each method can return to its caller.
3. Program Execution Stack Also contains memory the memory for the local variables used in each invocation of a method during an app's execution. This data, stored as a portion of the program-execution stack, is known as the activation record or stack frame of the method call
Stack Overflow A fatal error that occurs when more method calls occur than can have their activation records stored on the program-execution stack
Argument Promotion Implicitly converting an argument's value to the type that the method expects to receive(if possible) in its corresponding parameter
C#'s Promotion Rules Specify which conversions are allowed - that is, which conversions can be performed without losing data. If these rules are not satisfied, conversions will lead to compilation errors
1. Implicit Conversions Between Simple Types 1. Type[bool]..Conversion Types[no possible implicit conversions to other simple types]... 2. Type[byte]..Conversion Types[ushort, short, int, uint, ulong, long, decimal, float, or double]...
2. Implicit Conversions Between Simple Types 3. Type[char]..Conversion Types[ushort, int, uint, long, ulong, decimal, float, or double]... 4. Type[decimal]..Conversion Types[no possible implicit conversion to other simple types]...
3. Implicit Conversions Between Simple Types 5. Type[double]..Conversion Types[no possible implicit conversions to other simple types]... 6. Type[float]..Conversion Types[double]... 7. Type[int]..Conversion Types[long, decimal, float, or double]
4. Implicit Conversions Between Simple Types 8. Type[long]..Conversion Types[decimal, float, or double]... 9. Type[sbyte]..Conversion Types[short, int, long, decimal, float, or double]...
5. Implicit Conversions Between Simple Types 10. Type[short]..Conversion Types[int, long, decimal, float, or double]... 11. Type[uint]..Conversion Types[ulong, long, decimal, float, or double]...
6. Implicit Conversions Between Simple Types 12. Type[ulong]..Conversion Types[decimal, float, or double]... 13. Type[ushort]..Conversion Types[uint, int, ulong, long, decimal, float, or double]
Namespaces Many predefined classes are grouped into categories of related classes called namespaces. Together these namespeaces are referred to as the .NET Framework Class Library
1. .NET Framework Class Library Namespaces(a subset) 1. Namespace[System.Windows.Forms]..Description[Contains the classes required to create and manipulate GUIs]...
2. .NET Framework Class Library Namespaces(a subset) 2. Namespace[System.Windows.Controls, System.Windows.Input, System.Windows.Media, System.Windows.Shapes]..Description[Contain the classes of the Windows Presentation Foundation for GUIs, 2-D and 3-D graphics, multimedia, and animation]
3. .NET Framework Class Library Namespaces(a subset) 3. Namespace[System.Linq]..Description[Contains the classes that support Language Integrated Query(LINQ)... 4. Namespace[System.Data..Entity]..Description[Contains the classes for manipulating data in databases]
4. .NET Framework Class Library Namespaces(a subset) 5. Namespace[System.IO]..Description[Contains the classes that enable programs to input and output data]... 6. Namespace[System.Web]..Description[Contains the classes for creating and maintaining web apps, which are accessible over the internet]
5. .NET Framework Class Library Namespaces(a subset) 7. Namespace[System.Xml]..Description[Contains the classes for creating and manipulating XML data. Data can be read from or written to XML files]...
6. .NET Framework Class Library Namespaces(a subset) 8. Namespace[System.Xml.Linq]..Description[Contains the classes that support Language Integrated Query(LINQ) for XML documents]...
7. .NET Framework Class Library Namespaces(a subset) 9. Namespace[System.Collections, System.Collections.Generic]..Description[Contain the classes that define data structures for maintaining collections of data]...
8. .NET Framework Class Library Namespaces(a subset) 10. Namespace[System.Text]..Description[Contains classes that enable programs to manipulate characters and strings]
Objects of Class Random The element of chance can be introduced in an app via an object of class Random(of namespace System). Objects of class random can produce random byte, int, and double values.
Creating a Random Number Generator A new random--number generator object can be created as follows: Random randomNumbers = new Random();. The random-number generator object can then be used to generate random byte, int, and double values
Generating a Random Integer Consider following statement: int randomValue = randomNumbers.Next();. Method Next of class Random generates a random int value in range 0 to 2,147,483,646 inclusive. Every value in range has equal chance of being chosen each time method Next is called.
1. Pseudorandom Numbers A sequence of values produced by a complex mathematical calculation. The calculation uses current time of day to seed the random-number generator such that each execution of an app yields a different sequence of random values.
2. Pseudorandom Numbers Values returned by Next are in random integer generating statement are pseudorandom
1. Scaling the Range of Random Number Produced You might use statement... int randomValue = randomNumbers.Next(6);...which returns 0, 1, 2, 3, 4, or 5. The argument 6 - called the scaling factor - represents the number of unique values that next should produce(in this case, six -0, 1, 2, 3, 4, and 5)
2. Scaling the Range of Random Number Produced This manipulation is called scaling the range of values produces by Random method Next
1. Shifting the Range of Random Number Produced Suppose we wanted to simulate a six sided-die that has the numbers 1-6 on its faces, not 0-5. Scaling the range of values alone is not enough. So we shift the range of numbers produced.
2. Shifting the Range of Random Number Produced We could do this by adding a shifting value-in this case 1-to the result of method Next, as in... face = 1 + randomNumbers.Next(6);... The shifting value(1) specifies the first value in the desired set of random integers. This statement's range is 1-6
Combining Shifting and Scaling The following method receives two int arguments and returns a value from the first argument's value up to, but not including, the second argument's value... face = randomNumbers.Next(1, 7);... This statement's range is 1-6
1. Scaling and Shifting Random Numbers We can scale and shift random numbers using the following statement... number = randomNumbers.Next(shiftingValue, shiftingValue + scalingFactor);... where shiftingValue specifies the first number in the desired range of consecutive integers.
2. Scaling and Shifting Random Numbers The argument scalingFactor specifies how many number are in the range.
1. Producing Random Integer Sequence Other Than Ranges of Consecutive Integers We can use the generalized statement... number = shiftingValue + differenceBetweenValues * randomNumbers.Next(scalingFactor);...
2. Producing Random Integer Sequence Other Than Ranges of Consecutive Integers Where shiftingValue specifies the first number in the desired range of values, differenceBetweenValues represents the difference between consecutive numbers in the sequence and scalingFactor specifies how many numbers are in the range
1. Random-Number Repeatability for Testing and Debugging When debugging apps, it's sometimes useful to repeat the same sequence of pseudorandom numbers during each execution of the app. When repeatability is important, you can create a Random object as follows... Random randomNumbers = new Random(seedValue);..
2. Random-Number Repeatability for Testing and Debugging The seedValue argument(type int) seeds the random-number calculation. If the same seedValue is used every time, the Random object produces the same sequence of random numbers
1. Enumeration Declare a set of constants represented by identifiers. An enumeration is introduced by the keyword enum and a type name. As with a class, braces delimit the body of an enum declaration.
2. Enumeration Inside the braces is a comma-separated list of enumeration constants. The enum constant names must be unique, but the value associated with each constant need not be
Underlying Type of an enum You could also declare an enum's underlying type to be byte, sbyte, short, ushort, int, uint, long, or ulong by writing... private enum MyEnum : typeName{Constant1, Constant2, ...}... where typeName represents one of the intregral simple types
Scope of Declaration Is the portion of the app that can refer to the declared entity by its unqualified name. Such an entity is said to be "in scope" for that portion of the app
1. Basic Scope Rules 1. The scope of a parameter declaration is the body of the method in which the declaration appears... 2. The scope of a local-variable declaration is from the point at which the declaration appears to the end of the block containing the declaration...
2. Basic Scope Rules 3. The scope of a local-variable declaration that appears in the initialization section of a for statement's header is the body of the for statement and other expressions in the header...
3. Basic Scope Rules 4. The scope of a method, property, or field of a class is the entire body of the class. This enables non-static methods and properties of a class to use any of the class's fields, methods, and properties regardless of the order in which they're declared
Method Overloading When methods of the same name are declared in the same class but have different set of parameters(determined by the number, types, and the order of the parameter)
Calling Overloaded Methods When an overloaded method is called, the C# compiler selects the appropriate method by examining the number, types, and
Method's Signature A combination of the method's name and number, types and order of its parameters. The compiler distinguishes overloaded methods by their signature
1. Optional Parameters Methods can have optional parameters that allow the calling method to vary the number of arguments to pass. An optional parameter specifies a default value that's assigned to the parameter if the optional argument is omitted.
2. Optional Parameters All optional parameters must be placed to the right of the method's non-optional parameters - that is, at the end of the parameter list. Ex: public int Power(int baseValue, int exponentValue = 2);
1. Named Parameters C# doesn't allow you to skip an argument as shown in the preceding statement. C# provides a feature called named parameters, which enable you to call methods that receive optional parameters by providing only optional arguments you wish to specify.
2. Named Parameters To do so, you explicitly specify the parameter's name and value separated by a colon(:) in the argument list of the method call. The arguments for the required parameters must always be supplied
3. Named Parameters For the method...public void SetTime(int hour = 0, int minute = 0, int second = 0)...can be written as...t.SetTime(hour: 12, second: 22);...(assuming that we have a Time object named t[class Time]) to specify arguments only for the hour and second.
Recursive Method A method that calls itself, either directly or indirectly through another method
1. Recursive Call(Recursive Step) When a recursive method is called to solve a problem, it actually is capable of solving only the simplest case(s), or base case(s). If the method is called with a base case, it returns a result.
2. Recursive Call(Recursive Step) If the method is called with a more complex problem, it divides the problem into two conceptual pieces: a piece that the method known how to do and a piece that it does not know how to do.
3. Recursive Call(Recursive Step) To make recursion feasible, the latter piece must resemble the original problem looks like the original problem, the method calls a fresh copy(or several) of itself to work on the smaller problem; this is referred to as recursive call
Infinite Conversion Either omitting the base case or writing the recursion step incorrectly so that is does not converge on the base case will cause infinite recursion, eventually exhausting memory.
Passing Arguments Two ways to pass arguments to functions in many programming language are pass-by-value and pass-by-reference.
Passed-by-Value When an argument is passed by value(the default in C#), a copy of its value is made and passed to the called function. Changes to the copy do not affect the original variable's value in the caller
Passed-by-Reference When argument is passed by reference, caller gives method the ability to access and modify the caller's original value. To pass an object by reference into a method, simply provide as an argument in the method call the variable that refers to the object
ref and out Parameters What if you would like to pass a variable by reference so the called method can modify the variable's value? To do this, C# provides keywords ref and out.
ref Keyword Applying the ref keyword to a parameter declaration allows you to pass variables to a method by reference - called method will be able to modify original variable in caller. Is used for variables that already have been initialized in the calling method
1. out Keyword Preceding a parameter with keyword out creates an output parameter. This indicated to the compiler that the argument will be passed into the called method by reference and that the called method will assign a value to the original variable in the caller.
2. out Keyword If the method does not assign a value to the output parameter in every possible path of execution, the compiler generates an error
Returning Values with ref and out Parameters A method can return only one value to its caller via a return statement, but can return many values by specifying multiple output(ref and/or out) parameters
The Three Ways to Return Control to Caller The three ways to return control from a called method to a caller are using... 1. return;.. 2. return expression;.. 3. encountering the closing right brace of a method
Created by: TimC#Programming
Popular Engineering sets




Use these flashcards to help memorize information. Look at the large card and try to recall what is on the other side. Then click the card to flip it. If you knew the answer, click the green Know box. Otherwise, click the red Don't know box.

When you've placed seven or more cards in the Don't know box, click "retry" to try those cards again.

If you've accidentally put the card in the wrong box, just click on the card to take it out of the box.

You can also use your keyboard to move the cards as follows:

If you are logged in to your account, this website will remember which cards you know and don't know so that they are in the same box the next time you log in.

When you need a break, try one of the other activities listed below the flashcards like Matching, Snowman, or Hungry Bug. Although it may feel like you're playing a game, your brain is still making more connections with the information to help you out.

To see how well you know the information, try the Quiz or Test activity.

Pass complete!
"Know" box contains:
Time elapsed:
restart all cards