3 ms·
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
by zacharypinter 14y ago
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".