|
Hidden Gems in C# 2.0 (Continued)
However, in C# 2.0, you can ensure that the array is stored inline in the structure, as long as the structure is used only in unsafe code:
public struct MyArray
{
public fixed char MyName[50];
}
This second declaration takes 100 bytes. (Fixed size char buffers take 2 bytes per char.)
Finally, C# delegate declarations support Covariance and Contravariance. Covariance means that a delegate handler may specify a return type that is derived from the return type specified in the delegate signature. Contravariance means that a delegate handler may specify base classes for derived class arguments specified in the delegate signature. Because of covariance, this compiles:
public delegate object
Delegate1();
public static string func();
Delegate1 d = new Delegate1(
func );
func returns a type (string) that is derived from the type defined in the delegate signature (object).
Because of contravariance, this compiles:
public delegate void
Delegate2( string arg );
public static void func2(
object arg );
Delegate2 d2 = new Delegate1(
func2 );
func2 accepts a base class (object) of the type (string) defined as the argument for the delegate method. These additions will make it easier for you to create event handlers that handle multiple events: You can write one handler that receives a System.EventArgs parameter, and attach it to all events.
I've given you a small taste of some of the new features in C# 2.0 that have seen less coverage compared to the major new initiatives. But these features will change the way you write C# code, and change it for the better. You'll be able to create code that better expresses your designs, and is easier to maintain. By learning these features you'll be able to write less code that does more. That's what we all need.
About the Author
A commercial software developer and co-founder of SRT Solutions, Inc., Bill Wagner facilitates adoption of .NET in clients' product and enterprise development. His principal strengths include the core framework, the C# language, Smart Clients, and service-oriented architecture and design. In 2003 Microsoft recognized his .NET expertise, appointing him Regional Director for Michigan. Bill is the author of Effective C#. Reach him at .
Back to top
|