DCSIMG
Extension methods - IronShay

Browse by Tags

All Tags » Extension methods (RSS)

A Handy Extension Method: Retrieving Session Variables

[More handy extension methods: raise events safely , get the current page load mode ] Retrieving session variables is a daily task for web developers. In order to fetch a session variable, we should check if it exists and only then convert it to the expected type and use it. For example: int myVal; if (Session[ "MyVar" ] != null ) { int .TryParse(Session[ "MyVar" ], out myVal); } // ... more code ... This is an annoying practice which can be easily replaced by extension methods...

A Handy Extension Method: Raise Events Safely

Raising events is a very common practice. We do that a lot and it’s pretty irritating to check for nullity every time: if (eventHandler != null ) { eventHandler(sender, e); } Here comes extensions methods to our aid again. With only two extension methods, we can cover all possible event handlers and raise our events safely in one line. For example: MyEvent.RaiseSafe( this , EventArgs .Empty); Or MyEvent.RaiseSafe<MyEventArgs>( this , new MyEventArgs(someParameter)); In order to achieve that...

A Handy Extension Method: Get The Current Page Load Mode

I find myself pretty often write code to find out if I’m on a postback, callback or initial page load. I’ve decided to put an end to that and write an extension method to the ScriptManager class that will tell me the mode I’m in. This is what I came up with: public static class Extensions { public enum PageLoadMode { /// <summary> /// Occurs when the page is loaded for the first time. /// </summary> InitialPageLoad, /// <summary> /// Occurs on a regular postback. /// </summary>...

Extension Methods + Attributes = A Whole New World!

Earlier this week, a friend of mine (read his great blog here ) had tried to explain me why attributes were useful. We ended up with an extension method that reads attributes of enum values. Today I have the time to really think about that and I've just realized - this has tons of potential! Consider the following scenario - you have the following class: public string GetCityName( long userID) { // // Get data from some datasource... // return "Ney York City" ; } And now you're...