![]() ![]() ![]() The specific arguement about ForEach is that, based on the constraints on extension methods (namely that an extension method will never override an inherited method with the same signature), there may be a situation where the custom extension method is available on all classes that impelement IEnumerable except List. Writing an extension method to expose common functionality that does not return a value is a perfectly valid use. However, just because LINQ is implemented using extension methods does not mean that extension methods must be used in the same way and return a value. ![]() The LINQ extension methods do all return a value so they can be chained together: collection.Where(i => i.Name = "hello").Select(i => i.FullName) While this is a factual statement, it isn't entirely true. So there has been a lot of comments about the fact that a ForEach extension method isn't appropriate because it doesn't return a value like the LINQ extension methods. I wouldn't mind Microsoft adding a standard ForEach method in the next framework iteration. Those are all great points made by many people here and I can see why people are missing the function. ForEach() could be chained: although evilness/usefulness of such a feature is open to discussion.The syntax to call a delegate is indeed much simpler: objects.ForEach(DoSomething).Type checking: foreach is done at runtime, ForEach() is at compile time (Big Plus!).Here are the major differences between the statement and the method: However, I must admit I changed my stance on that issue a ForEach() extension method would indeed be useful in some situations. The latter is clearer and easier to read in most situations, although maybe a bit longer to type. I'd hate to see the following: list.ForEach( item => There is already a foreach statement included in the language that does the job most of the time. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |