CHAPTER 3 CORE C# PROGRAMMING CONSTRUCTS, PART I
LINQ for a very long time, or open the compiled image in ildasm.exe. The good news is that when you
are using LINQ, you seldom (if ever) care about the underlying type of the query’s return value; you will
simply assign the value to an implicitly typed local variable.
In fact, it could be argued that the only time one would make use of the var keyword is when
defining data returned from a LINQ query. Remember, if you know you need an int, just declare an int!
Overuse of implicit typing (via the var keyword) is considered by most developers to be poor style in
production code.
Source Code The ImplicitlyTypedLocalVars project can be found under the Chapter 3 subdirectory.
C# Iteration Constructs
All programming languages provide ways to repeat blocks of code until a terminating condition has been
met. Regardless of which language you have used in the past, I would guess the C# iteration statements
should not raise too many eyebrows and should require little explanation. C# provides the following four
iteration constructs:
•
for loop
•
foreach/in loop
•
while loop
•
do/while loop
Let’s quickly examine each looping construct in turn, using a new Console Application project
named IterationsAndDecisions.
Note I will keep this final section of the chapter short and to the point, as I am assuming you have experience
using similar keywords (if, for, switch, etc.) in your current programming language. If you require more
information, look up the topics “Iteration Statements (C# Reference),” “Jump Statements (C# Reference),” and
“Selection Statements (C# Reference)” within the .NET Framework 4.5 SDK documentation.
The for Loop
When you need to iterate over a block of code a fixed number of times, the for statement provides a
good deal of flexibility. In essence, you are able to specify how many times a block of code repeats itself,
as well as the terminating condition. Without belaboring the point, here is a sample of the syntax.
// A basic for loop.
static void ForLoopExample()
{
// Note! "i" is only visible within the scope of the for loop.
112