Methods: A Deeper Look
- 7.1 Introduction
- 7.2 Packaging Code in C#
- 7.3 static Methods, static Variables and Class Math
- 7.4 Methods with Multiple Parameters
- 7.5 Notes on Using Methods
- 7.6 Argument Promotion and Casting
- 7.7 The .NET Framework Class Library
- 7.8 Case Study: Random-Number Generation
- 7.9 Case Study: A Game of Chance; Introducing Enumerations
- 7.10 Scope of Declarations
- 7.11 Method-Call Stack and Activation Records
- 7.12 Method Overloading
- 7.13 Optional Parameters
- 7.14 Named Parameters
- 7.15 C# 6 Expression-Bodied Methods and Properties
- 7.16 Recursion
- 7.17 Value Types vs. Reference Types
- 7.18 Passing Arguments By Value and By Reference
- 7.19 Wrap-Up
Paul and Harvey Deitel take a deep look at methods in C# through a series of object-oriented programming case studies.
In this chapter, we take a deeper look at methods. We’ll discuss the difference between non-static and static methods. You’ll see that the Math class in the .NET Framework Class Library provides many static methods to perform mathematical calculations. We’ll also discuss static variables (known as class variables) and why method Main is declared static.
You’ll declare a method with multiple parameters and use operator + to perform string concatenations. We’ll discuss C#’s argument promotion rules for implicitly converting simple-type values to other types and when these rules are applied by the compiler. We’ll also present several commonly used Framework Class Library namespaces.
We’ll take a brief, and hopefully entertaining, diversion into simulation techniques with random-number generation and develop a version of a popular casino dice game that uses most of the programming techniques you’ve learned so far. You’ll declare named constants with the const keyword and with enum types. We’ll then present C#’s scope rules, which determine where identifiers can be referenced in an app.
We’ll discuss how the method-call stack enables C# to keep track of which method is currently executing, how local variables of methods are maintained in memory and how a method knows where to return after it completes execution. You’ll overload methods in a class by providing methods with the same name but different numbers and/or types of parameters, and learn how to use optional and named parameters.
We’ll introduce C# 6’s expression-bodied methods, which provide a concise notation for methods that simply return a value to their caller. We’ll also use this expression-bodied notation for a read-only property’s get accessor.
We’ll discuss how recursive methods call themselves, breaking larger problems into smaller subproblems until eventually the original problem is solved. Finally, we’ll provide more insight into how value-type and reference-type arguments are passed to methods.