Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

313
Views
IEnumerable<T> from Enumerable.FromRange().Select() vs ToList()

This really stumped me, as I expected 'pass by reference' behavior. I expected this code to print "5,5,5", but instead it prints "7,7,7".

IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 });
Alter(list);
Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
Console.ReadLine();

void Alter(IEnumerable<MyObj> list)
{
    foreach(MyObj obj in list)
    {
        obj.Name = 5;
    }
}

class MyObj
{
    public int Name { get; set; }
}

Whereas this prints "7,7,7" as expected.

IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 }).ToList();
Alter(list);
Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));
Console.ReadLine();

void Alter(IEnumerable<MyObj> list)
{
    foreach(MyObj obj in list)
    {
        obj.Name = 5;
    }
}

class MyObj
{
    public int Name { get; set; }
}

Obviously this is a simplified version of the actual code I was writing. This feels a lot more like behavior I've run into with a property that instantiates a new instance of an object. Here I understand why I would get a new instance every time I reference Mine.

public MyObj Mine => new MyObj();

I was just very surprised to see this behavior in the above code, where it feels more like I've "locked in" the enumerated objects. Can anyone help me understand this?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Select produces an object that has lazy evaluation. This means all steps are executed on demand.

So, when this line gets executed:

IEnumerable<MyObj> list = Enumerable.Range(0, 3).Select(x => new MyObj { Name = 7 });

no MyObj instance is created yet - only the enumerable that has all the information to compute what you've indicated.

When you call Alter, this gets executed during iteration via foreach and all objects get 5 assigned to their properties.

But when you print it, everything gets executed again here:

Console.WriteLine(string.Join(',',list.Select(x => x.Name.ToString())));

So during execution of string.Join, brand new MyObj instances are created with new MyObj { Name = 7 } and printed.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!