Extension Method Round Up

Extension methods in c# have definitely changed my day to day development in a positive way, as they can easily add functionality that may be missing in the base class library or provide easy access to routines that you may use frequently. Many times they can just make a snippet of code more terse or readable. Here are two extension methods I came across on StackOverflow that come in handy for firing events:

  1. static public void RaiseEvent(this EventHandler theEvent, object sender, EventArgs e)
  2. {
  3. if (theEvent != null)
  4. theEvent(sender, e);
  5. }
  7. static public void RaiseEvent<T>(this EventHandler<T> theEvent, object sender, T e)
  8. where T : EventArgs
  9. {
  10. if (theEvent != null)
  11. theEvent(sender, e);
  12. }

which can be used like such:

  1. SomthingHappenedEvent.RaiseEvent(this, new EventArgs());

another useful extension method for passing in a property name without using hardcoded strings:

  1. public static string GetPropertyName<T, S>(this T obj, Expression<Func<T, S>> expr)
  2. {
  3. return ((MemberExpression)expr.Body).Member.Name;
  4. }

which can be used as such:

  1. var ob = new { SomeProp = "abc"};
  2. string propName = ob.GetPropertyName(a => a.SomeProp);

and finally, another handy set for quickly serializing any object to JSON:

  1. public static string ToJson(this object obj)
  2. {
  3. var serializer = new JavaScriptSerializer();
  4. return serializer.Serialize(obj);
  5. }
  7. public static string ToJson(this object obj, int recursonDepth)
  8. {
  9. var serializer = new JavaScriptSerializer();
  10. serializer.RecursionLimit = recursonDepth;
  11. return serializer.Serialize(obj);
  12. }

Tags: , ,

You can follow any responses to this entry through the RSS 2.0 feed. You can skip to the end and leave a response. Pinging is currently not allowed.

Leave a Reply

You must be logged in to post a comment.