Delegates
Posted by Jonathan Ng | Filed under Technical
Sometimes, you want write a method that will receive another method as a parameter. You might not know at compile time, what that method is. Remember in object oriented programming, methods do not exist in isolation, but are associated to objects. Hence, you won’t know what object the method belongs to either. However, in order for your method to work, you have certain expectations of the method that you receive as parameter before making a call to it. This means that you’ll know what goes in to the method, at what it returns.
That’s where delegates come in. A delegate is a special type of object where you wrap up these details (including the method signature for type safety) of the method you want to be passed around. So in the example above, you declare a delegate (outside of the method), say DelegateA. Then in your method signature, you specify that it expects a delegate of type DelegateA. Hence, it can be said that delegates gives a name to a method signature.
Delegates are type safe in the sense that they validate the signature of the method being called. However, delegates do not care about what type of object the method is being called against or even whether the method is a static method or instance method.
One way of using delegates is to group methods together in an array, so you can call several methods in a loop. As delegates are objects, not only can you create an array of delegates, you can pass them as parameters to other methods. Read the rest of this entry »
Enumerations
Posted by Jonathan Ng | Filed under Technical
This is the first of a series of posts about C#. Since I can’t really think of tiny apps to put stuff that I’ve learned to practice, the least I can do is blog about it, hopefully to boost my memory on it. So let’s get on with it..
In short, an enumeration is a user-defined interger type. Let’s say you want to define the colors of a traffic light. Defining them with strings has it’s associated overheads. The most memory-efficient way is to use integers to represent the colors: say, 1 for red, 2 for yellow, 3 for green. Problem is, the numbes 1, 2 and 3 aren’t really self-explaining. One might mistake 3 for red for example. The next best way is to use some constants: Read the rest of this entry »
Tags: C#, general_programming