none
Proposal: Generic Extension Methods RRS feed

  • Question

  • namespace ConsoleApplication1
    {
        using System;
        using System.Collections.Generic;
    
        static class Program
        {
            static void Main(string[] args)
            {
                var M = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 9 };
                var L = M.Map(x => x * x);
            }
        }
    
        internal static class ListExtensions<T>
        {
            static public List<T> Map(this List<T> elements, Func<T, T> f)
            {
                var result = new List<T>();
                foreach (var x in elements)
                    result.Add(f(x));
    
                return result;
            }
        }
    }

    I guess, my proposal is self-explaining. Either add a generic extension like "ForEach" that takes a Func<> instead of an Action<>, or, even better, implement generic method extensions. Icing on the cake for 4.5, but a must-have for 5.0.

    Kind regards,

    Carsten

    PS: Not even in F# lets something like this look nice:

    module Foo
      let f x = x * x
      let M = [ 0 .. 9 ]
      let L = M |> List.map f

    Why not simply

    module Foo
      let f x = x * x
      let M = [ 0 .. 9 ]
      let L = f M // operator syntax
      // or let L = f(M) // vector function syntax
      // or f|>M = L // "f applied to M gives L"
      // or, C# style, let L = M.f
      // or, my fav, let L = M<-f
      // or, a bit more math:
      // let L = {M|f}
      // even let L = {M|A(f)} would be nice, "for every
      // element of M, apply f, and let the result be
      // part of L"

    Nicest version would be

    let L = {M|∀f}

    but I guess we don't want no APL ;)

    Monday, May 7, 2012 5:50 PM

Answers

All replies