Writing Truely Generic Code in C#
Bruce Eckles continues his great rant on “weak typing.” What seems to be missed by this discussion is that you can actually write generic code in C# without too much difficulty. Delegates provide us a very nice interface independant way to make method calls. For example:
public delegate void speak(string text);
public class person
{
public void speak(string text) { ... }
}public class robot
{
public void speak(string text) { ... }
}
Now, you can make the robot or the person speak by coding:
robot r = new robot();
speak speaker = new speak(r.speak);
speaker(“say something“);
This is actually more powerful than relying on the semantics (ie. the name) of the method, because of situtations when you have a new class where the name “speak“ doesn't exactly fit for communication:
public class dog
{
public void bark(string text) { ... }
}
A dog doesn't speak, but it does bark, so now I can write:
dog d = new dog();
speak speaker = new speak(d.bark);
speaker(“say something“);
And everything continues to work.