News for hackers. Stuff that matters.
Re:C# Extension Methods Demystified by zacharypinter on Friday March 29, 2013 @12:13AM (#5459211)
One of my favorite uses of extension methods is to have semi-intelligent type coercers/converters.

For example:

  public static string AsString(this object me, string defaultValue = null)                                     
  public static int AsInt(this object me, int defaultValue = default(int))                                      
  public static float AsFloat(this object me, float defaultValue = default(float))                              
  public static double AsDouble(this object me, double defaultValue = default(double))                          
  public static Uri AsUri(this object me, Uri defaultValue = null)                                              
  public static bool AsBool(this object me, bool defaultValue = default(bool))
It's handy because you can do null checking in the extension method. Additionally, you can add some extra logic for converting specific runtime types. For example, calling .AsBool() on a string can check if the contents of the string is "1" or "true".

There are no comments on this comment yet.