CHAPTER 11 ADVANCED C# LANGUAGE FEATURES
}
}
// Use int* variable here!
// pt is now unpinned, and ready to be GC-ed once
// the method completes.
Console.WriteLine ("Point is: {0}", pt);
In a nutshell, the fixed keyword allows you to build a statement that locks a reference variable in
memory, such that its address remains constant for the duration of the statement (or scope block). Any
time you interact with a reference type from within the context of unsafe code, pinning the reference is a
must.
The sizeof Keyword
The final unsafe-centric C# keyword to consider is sizeof. As in C(++), the C# sizeof keyword is used to
obtain the size in bytes of a value type (never a reference type), and it may only be used within an unsafe
context. As you might imagine, this ability can prove helpful when you’re interacting with unmanaged
C-based APIs. Its usage is straightforward.
unsafe static void UseSizeOfOperator()
{
Console.WriteLine("The size of short is {0}.", sizeof(short));
Console.WriteLine("The size of int is {0}.", sizeof(int));
Console.WriteLine("The size of long is {0}.", sizeof(long));
}
As sizeof will evaluate the number of bytes for any System.ValueType-derived entity, you can obtain
the size of custom structures as well. For example, we could pass the Point structure into sizeof, as
follows:
unsafe static void UseSizeOfOperator()
{
...
Console.WriteLine("The size of Point is {0}.", sizeof(Point));
}
Source Code The UnsafeCode project can be found under the Chapter 11 subdirectory.
That wraps up our look at some of the more advanced features of the C# programming language. To
make sure we are all on the same page here, I again must say that a majority of your .NET projects might
never need to directly use these features (especially pointers). Nevertheless, as you will see in later
chapters, some topics are quite useful, if not required, when working with the LINQ APIs, most notably
extension methods and anonymous types.
437