I’ve been playing around with some c# extensions lately and I have a question. I made a ‘ForEach’ extension for IEnumerables (List has one from Linq, though none exists for IEnumerables.) It’s a very simple one:
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());
Though now I was wondering, can I take it one step further and make it something like: MyArray.ForEach(ElementMethod);?
Edit: Already some interesting answers, though I was trying 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 can’t know that ‘action’ is a method of T, so this doesn’t work 🙁 Perhaps there’s a way to ensure the compiler of this? Something like public static void CallOnEach<T> (this IEnumerable<T> source, Action action) where action isFunctionOf T
Thanks!
If
ElementMethodis of typeAction<T>you can use it right now with your extension. And it is the same likestatic voidmethod of typeT:But there is no way how to make it more generic. You can’t call some method on your element without reference to it.
IMHO: There is no big deal. You are saving just few characters.