I know that String extension methods return a String and do not actually affect the variable calling the extension method (so it's immutable) - but how do I tell whether other extension methods do or not? For example, I'm working with a List<NewsItem>
- and I need to order this list by date descending, so I've written this code:
newsItems.OrderByDescending(o => o.Date);
Does this affect the newsItems list or just return the IOrderedEnumerable??
In other words, should the above code actually read:
newsItems = newsItems.OrderByDescending(o => o.Date).ToList();
??
Thanks,
Dan
OrderByDescending
is an extension method onIEnumerable<T>
, which itself provides read-only access. Of course, the extension method could cast toList<T>
, but basically none of the LINQ to Objects extension methods affect their target (assuming the targets aren't affected by iteration, of course).LINQ is designed in a functional style - methods return a new view on the data rather than changing the target they're called on.
EDIT: As noted by drew, the
[Pure]
attribute can be used as an indication of this, and some tools will pick up on it. However:[Pure]
attribute has been correctly applied[Pure]
attribute (it doesn't show up in the docs I linked to, for example)