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 learn how to 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.