Monthly Archives: November 2010

Nice Features in C#

I worked several years with Objective-C and then several years intensively with Java and now more frequently with C#.

Each language/environment has it’s amenities and quirks.

Depending on the task to accomplish, sometimes one thinks, ah this has been pleasantly solved. My favorites in C# so far:

Multicast-Delegates

A normal Delegate in C# looks like:

public delegate float Compute(float n);

public float Square(float n)
{
    return n * n;
}

public float Faculty(float n)
{
    return n == 0 ? 1 : n * Faculty(n - 1);
}

Calling the delegate looks like:

Compute function = Faculty;
Console.Write(function(7));
function = Square;
Console.Write(function(1.4142135623731f));

A Multicast-Delegate references multiple target methods. With += you add a delegate and with -= you remove a delegate, e.g.

MyDelegate md = aDelegateToCall1;
md += aDelegateToCall2;

Unsafe and Pointer

If you have identified a real hotspot in your program and you have to optimize it or if you must call some native stuff you can simply leave the managed area with the keyword unsafe.



unsafe void Filter(Bitmap img) 
{
 ...
 var data = img.LockBits(rect, ImageLockMode.ReadWrite, img.PixelFormat);
 byte* ptr = (byte*)data.Scan0;
 //manipulate img
}

This is definitely more comfortable then using Java Native Interface (JNI) in a Java environment.

Operator Overloading

Like the feature above when used with care operator overloading is a nice thing. A good example is the operator ‘==’ for strings in C#. In Java with a==b you check for identity (are a and b referencing the same object) and not whether the content of a equals the content of b.
Also when working with vectors and matrices in computer graphics overloading operators like +, and * is very comfortable.

Output Parameters

Especially sometimes when writing trivial methods that should return more then one value, output parameters are coming in handy.

        public void GetVersion(out int major, out int minor)        
        {
            major = 10;
            minor = 4;
        }

Called is it the following way:

            int major;
            int minor;

            GetVersion(out major, out minor);