c# - Passing an object to a method and then calling an extenstion method on that object -
i working on method yesterday , ran strange, here dumbed down version of code: problem orderby applied in bar.populatelist method not persisting.
class foo { list myobjects; public void populatemyobjects() { //items added list orderby not persisting. bar.populatelist(myobjects); } } class bar { public static int populatelist(list thelist) { foreach(var in webserbicecall) { thelist.add(var); } // orderby call sorts 'thelist' in context of method. // when return method thelist has been populated ordering has // reverted order items added list. thelist.orderby(obj => obj.id); return thelist.count; } }
now if update code , add ref keyword per below works: e.g. public static int populatelist(ref list thelist) , bar.populatelist(ref myobjects);
can enlighten me? thought objects passed ref? fact orderby extension method?
thanks, cian
the problem here orderby
call not mutate thelist
in way. instead returns new ienumerable<object>
ordered. hence why not see affects of call outside method, it's not changing object.
using orderby
method creates new value , hence if want calling function aware of new value must returned in manner. common places in return value or in ref
/out
param.
public static int populatelist(ref list<object> thelist) { ... thelist = thelist.orderby(obj => obj.id).tolist(); }
Comments
Post a Comment