Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 160963
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 11, 20262026-05-11T11:07:42+00:00 2026-05-11T11:07:42+00:00

I’m learning a bit about function programming, and I’m wondering: 1) If my ForEach

  • 0

I’m learning a bit about function programming, and I’m wondering:

1) If my ForEach extension method is pure? The way I’m calling it seems violate the ‘don’t mess with the object getting passed in’, right?

public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {   foreach ( var item in source )      action(item); }   static void Main(string[] args) {     List<Cat> cats = new List<Cat>()     {         new Cat{ Purring=true,Name='Marcus',Age=10},         new Cat{ Purring=false, Name='Fuzzbucket',Age=25 },         new Cat{ Purring=false, Name='Beanhead',Age=9 },         new Cat{Purring=true,Name='Doofus',Age=3}     };       cats.Where(x=>x.Purring==true).ForEach(x =>     {         Console.WriteLine('{0} is a purring cat... purr!', x.Name);     });      // *************************************************     //  Does this code make the extension method impure?     // *************************************************     cats.Where(x => x.Purring == false).ForEach(x =>     {         x.Purring = true; // purr,baby     });      // all the cats now purr     cats.Where(x=>x.Purring==true).ForEach(x =>     {         Console.WriteLine('{0} is a purring cat... purr!', x.Name);     }); }  public class Cat {         public bool Purring;         public string Name;         public int Age; } 

2) If it is impure, is it bad code? I personally think it makes cleaner looking code than the old foreach ( var item in items) { blah; }, but I worry that since it might be impure, it could make a mess.

3) Would it be bad code if it returned IEnumerable<T> instead of void? I’d say as long as it is impure, yes it would be very bad code as it would encourage chaining something that would modify the chain. For example, is this bad code?

// possibly bad extension public static IEnumerable<T> ForEach<T>(this IEnumerable<T> source, Action<T> action) {     foreach ( var item in source )         action(item);      return source;  } 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. 2026-05-11T11:07:43+00:00Added an answer on May 11, 2026 at 11:07 am

    Impurity doesn’t necesarily mean bad code. Many people find it easy and useful to use side effects to solve a problem. The key is first knowing how to do it in a pure way, so you’ll know when impurity is appropriate :).

    .NET doesn’t have the concept of purity in the type system, so a ‘pure’ method that takes in arbitrary delegates can always be impure, depending on how it’s called. For instance, ‘Where’, aka ‘filter’, would usually be considered a pure function, since it doesn’t modify its arguments or modify global state.

    But, there’s nothing stopping you from putting such code inside the argument to Where. For example:

    things.Where(x => { Console.WriteLine('um?');                      return true; })       .Count(); 

    So that’s definately an impure usage of Where. Enumerables can do whatever they want as they iterate.

    Is your code bad? No. Using a foreach loop is just as ‘impure’ — you’re still modifying the source objects. I write code like that all the time. Chain together some selects, filters, etc., then execute a ForEach on it to invoke some work. You’re right, it’s cleaner and easier.

    Example: ObservableCollection. It has no AddRange method for some reason. So, if I want to add a bunch of things to it, what do I do?

    foreach(var x in things.Where(y => y.Foo > 0)) { collection.Add(x)); }  

    or

    things.Where(x => x.Foo > 0).ForEach(collection.Add); 

    I prefer the second one. At a minimum, I don’t see how it can be construed as being worse than the first way.

    When is it bad code? When it does side effecting code in a place that’s not expected. This is the case for my first example using Where. And even then, there are times when the scope is very limited and the usage is clear.

    Chaining ForEach

    I’ve written code that does things like that. To avoid confusion, I would give it another name. The main confusion is ‘is this immediately evaluated or lazy?’. ForEach implies that it’ll go execute a loop right away. But something returning an IEnumerable implies that the items will be processed as needed. So I’d suggest giving it another name (‘Process’, ‘ModifySeq’, ‘OnEach’… something like that), and making it lazy:

    public static IEnumerable<T> OnEach(this IEnumerable<T> src, Action<T> f) {   foreach(var x in src) {     f(x);     yield return x;   } } 
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 433k
  • Answers 433k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer Not all implementations of List<...> allow for elements to be… May 15, 2026 at 3:03 pm
  • Editorial Team
    Editorial Team added an answer Ask the UITabBarController about its selectedIndex might help if your… May 15, 2026 at 3:03 pm
  • Editorial Team
    Editorial Team added an answer You want to use the third one there, except plural… May 15, 2026 at 3:03 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.