Method Call on All IEnumerable Members

I have been playing around with some C # extensions lately and have a question. I made a "ForEach" extension for IEnumerables (List has one of Linqs, although it doesn't exist for IEnumerables). It's very simple:

public static void ForEach<T> (this IEnumerable<T> source, Action<T> action)
{
    foreach (T element in source) {
        action(element);
    }
}

      

And you call it like MyArray.ForEach(element=>element.ElementMethod());

Although now I was wondering if I could go one step further and do something like MyArray.ForEach(ElementMethod);

:?

Edit: There are some interesting answers already, although I tried something like this:

public static void CallOnEach<T> (this IEnumerable<T> source, Action action)
{
    foreach (T element in source) {
        element.action();
    }
}

      

Of course, the compiler cannot know that "action" is a method of T, so this doesn't work :( Perhaps there is a way the compiler can provide this? Something like public static void CallOnEach<T> (this IEnumerable<T> source, Action action) where action isFunctionOf T

Thank!

+3


source to share


2 answers


If it ElementMethod

has a type Action<T>

, you can use it right now with your extension. And it looks like a method static void

like T

:

public static void ElementMethod<T>(T parameter){}

//or

public static void ElementMethod(MyElement element){}

      

But there is no way to make it more general. You cannot call any method on your element without referencing it.



IMHO: No big deal. You only save a few characters.

MyArray.ForEach(e=>e.ElementMethod());
MyArray.ForEach(ElementMethod);1234567 - // characters saved ;-)

      

+2


source


You can make ElementMethod an extension method and you can make Latter



+1


source







All Articles