Prev | Current Page 299 | Next

Jon Skeet

"C# in Depth: What you need to master C# 2 and 3"

This
may not sound like a big deal, but in many situations it??™s enormously handy??”you can
use contextual information that you have ???on hand??? rather than having to set up extra
types just to store data you already know. We??™ll see some useful concrete examples
soon, I promise??”but first it??™s worth looking at some code to clarify these definitions.
Listing 5.10 provides an example with a number of local variables. It??™s just a single
method, so it can??™t be run on its own. I??™m not going to explain how it would work or
what it would do yet, but just explain how the different variables are classified.
void EnclosingMethod()
{
int outerVariable = 5;
string capturedVariable = "captured";
if (DateTime.Now.Hour==23)
{
int normalLocalVariable = DateTime.Now.Minute;
Console.WriteLine(normalLocalVariable);
}
ThreadStart x = delegate()
{
string anonLocal="local to anonymous method";
5 This is general computer science terminology, not C# terminology.
6 Excluding ref and out parameters.
Listing 5.10 Examples of different kinds of variables with respect to anonymous methods
Outer variable
(uncaptured)
B C Outer variable
captured by
anonymous
method
D Local variable of
normal method
E Local variable
of anonymous
method
152 CHAPTER 5 Fast-tracked delegates
Console.WriteLine(capturedVariable + anonLocal);
};
x();
}
Let??™s go through all the variables from the simplest to the most complicated:
?–  normalLocalVariable d isn??™t an outer variable because there are no anonymous
methods within its scope.


Pages:
287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311