C H A P T E R 11
Advanced C# Language Features
In this chapter, you’ll deepen your understanding of the C# programming language by examining a
number of more advanced syntactic constructs. To begin, you’ll learn how to implement and use an
indexer method. This C# mechanism enables you to build custom types that provide access to internal
subitems using an array-like syntax. After you learn how to build an indexer method, you’ll see how to
overload various operators (+, -, <, >, and so forth), and how to create custom explicit and implicit
conversion routines for your types (and you’ll learn why you might want to do this).
Next, you’ll examine topics that are particularly useful when working with LINQ-centric APIs
(though you can use them outside of the context of LINQ)—specifically extension methods and
anonymous types.
To wrap things up, you’ll learn how to create an “unsafe” code context in order to directly
manipulate unmanaged pointers. While it is certainly true that using pointers in C# applications is a
fairly infrequent activity, understanding how to do so can be helpful in some circumstances that involve
complex interoperability scenarios.
Understanding Indexer Methods
As a programmer, you are certainly familiar with the process of accessing individual items contained
within a simple array using the index operator ([]). For example:
static void Main(string[] args)
{
// Loop over incoming command-line arguments
// using index operator.
for(int i = 0; i < args.Length; i++)
Console.WriteLine("Args: {0}", args[i]);
// Declare an array of local integers.
int[] myInts = { 10, 9, 100, 432, 9874};
}
// Use the index operator to access each element.
for(int j = 0; j < myInts.Length; j++)
Console.WriteLine("Index {0} = {1} ", j, myInts[j]);
Console.ReadLine();
This code is by no means a major newsflash. However, the C# language provides the capability to
design custom classes and structures that may be indexed just like a standard array, by defining an
399