I have a collection of objects, and want to modify a property on an object in that collection. If I have a single object, my ChangeStuff
method works fine, and the object is modified when returning from the method. (First 4 lines in Main)
However, when iterating through the collection, I guess I'm missing something, as my changed values seem to be stuck in the scope of the foreach loop.
I shouldn't have to pass the objects by ref (or using an out parameter), since I'm not returning a new value.
Sorry for the big code chunk, but it's about as simplified as I can make it and still demonstrate my issue.
class foobar
{
public string string1;
public string string2;
}
static void Main(string[] args)
{
/***** THIS WORKS!! *****/
foobar singleFb = new foobar { string1 = "foo2", string2 = "bar2" };
ChangeStuff(singleFb);
Console.WriteLine(singleFb.string1 + ", " + singleFb.string2);
Console.ReadLine(); //pause to read output
/***** THIS DOESN'T WORK!! *****/
List<foobar> myList = new List<foobar> { new foobar {string1 = "foo1", string2 = "bar1"}, new foobar {string1 = "foo2", string2 = "bar2"}, new foobar {string1 = "something else", string2 = "something else again"} };
IEnumerable<foobar> fbs = myList.Where(x => x.string1.StartsWith("foo"));
ChangeStuff(fbs);
foreach (foobar fb in fbs)
{
Console.WriteLine(fb.string1 + ", " + fb.string2);
}
Console.ReadLine(); //pause to read output
}
static void ChangeStuff(IEnumerable<foobar> fbs)
{
foreach (foobar fb in fbs)
{
ChangeStuff(fb);
}
}
static void ChangeStuff(foobar fb)
{
if (fb.string1.Contains("2"))
fb.string1 = "changed!";
}
}
What do I need to change in order to modify an object in a collection?
Edit: Also, just noticed that my collection is actually completely missing "foo2" when it comes back... Weird. I'm actually using IQueryable in my application, and haven't experienced this problem. ie. I have all the objects, they just aren't correctly modified. Not sure what's going on here...
Edit 2: Thank you for your answers, it makes perfect sense now. If I change my
ChangeStuff
method as follows, it works as I would expect:
static void ChangeStuff(foobar fb)
{
if (fb.string2.Contains("2"))
fb.string2 = "changed!";
}