C sharper with Extensions

Here’s another post to continue on the Java developer C# experience.

Extension classes, with naming convention of Extensions.cs

public enum Fruits {
  Apple,
  Banana,
  Orange
}

public static class FruitsExtensions {
  public static bool IsRed(this Fruits fruit) {
     return fruit == Fruits.Apple;
  }
}

this would allow you to do

var myfruit = Fruits.Apple;
myfruit.IsRed();

It looks like a Decorator pattern, except upon reading more, the extensions miss the dynamic properties of the design pattern – it cannot alter behaviors of the existing class. All it does is to provide a way to add static method to an existing class. So it is NOT a Decorator.

Again, the Visual Studio peek definition doesn’t help again. It shows the class with empty methods. A search for the entire project helped though. The code was embedded in a common class.

Why do Java Developers wear glasses?

Because they are nerdy? 😎

No, because they don’t C# (see sharp). 😛

hahhaa. ok but seriously I am ramping up on some C# ASP.NET legacy project. Luckily I do not wear glasses!

So today I came across this code that has to do with events, but I have no idea once the event is raised, who’s listening, and what follows.

public delegate void MyEventHandler(String someArg);

public event MyEvent MyEvent;

private void onMyEvent() {
  if (MyEvent != null) {
    MyEventHandler("hello");
  }
}

public void doSomething() {
  // do something and trigger the event
  onMyEvent();
}

So first up, what’s a delegate? it’s a function pointer that’s safe. ok.
and a keyword “event”. That’s self-explanatory.
I see that the code did something and has raised the event. BUT who’s listening?? and what happens after the event is raised?
Visual Studio’s find call hierarchy, view reference, Alt+F12 are not helping.

and then… few searches later, I found this code in one of the aspx pages…

<uc15:UCMySection ID="UCMySection" runat="server" OnMyEvent="UCMySection _DoSomethingElse"/>

Ohhhhhhhhh. It’s the aspx page user control listening… I get it now.

I like how on the C# side, the raising event is easy to do. But not sure about the ASP.NET part. Glad we can say bye to that soon.

On a semi-related note on events and publish and subscribe, I am working on another pubsub thing for reliable message delivery. Excited to get real project experience with Kafka (previous project) and RabbitMQ (new project)!