Home

my extensions 101

Can somebody post (or link to) and example of something that was implemented in my extension?

Comments

  • My Extensions:
    void Main()
    {
      // Write code to test your extensions here. Press F5 to compile and run.
    }
    
    public static class MyExtensions
    {
      // Write custom extension methods here. They will be available to all queries.
    
      public static int Sum(int a, int b)
      {
        return a + b;
      }
    }
    
    // You can also define non-static classes, enums, etc.

    Query (Move 'using' directory into Query Properties: Yes):
    using static MyExtensions;
    
    Sum(1, 2).Dump();
  • Simple example:
    public static class MyExtensions
    {
      public static bool Contains (this string s, string value, bool ignoreCase) =>
        s.IndexOf (value, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) > -1;
    }
    To use:

    "FOO".Contains ("oo", true).Dump(); // case-insensitive

    Another example:
    public static class MyExtensions
    {
        public static bool IsNumeric (this Type t)
        {
            if (t == null) return false;
    
            t = t.CollapseNullable();
    
            if (t == typeof (decimal)) return true;
            if (!t.IsPrimitive) return false;
            return t != typeof (char) && t != typeof (bool);
        }
    
        public static Type CollapseNullable (this Type t)
        {
            if (t == null) return null;
            bool nullable = t.IsGenericType && t.GetGenericTypeDefinition () == typeof (Nullable<>);
            if (nullable) t = t.GetGenericArguments () [0];
            return t;
        }
    }
    
    …
    
    typeof (int).IsNumeric().Dump();     // true
    typeof (float?).IsNumeric().Dump();  // true
    typeof (char).IsNumeric().Dump();    // false
  • Thanks for showing *actual* extensions methods ;)
Sign In or Register to comment.