tags

Tuple

Using foreach with index in C#

Just a quick tip today! for and foreach loops are among the most useful constructs in a C# developer’s toolbox. To iterate a collection, foreach is, in my opinion, more convenient than for in most cases. It works with all collection types, including those that are not indexable such as IEnumerable<T>, and doesn’t require to access the current element by its index. But sometimes, you do need the index of the current item; this usually leads to one of these patterns:

Tuple deconstruction in C# 7

Last time on this blog I talked about the new tuple feature of C# 7. In Visual Studio 15 Preview 3, the feature wasn’t quite finished; it lacked 2 important aspects: emitting metadata for the names of tuple elements, so that the names are preserved across assemblies deconstruction of tuples into separate variables Well, it looks like the C# language team has been busy during the last month, because both items are now implemented in VS 15 Preview 4, which was released today!

Tuples in C# 7

A tuple is an finite ordered list of values, of possibly different types, which is used to bundle related values together without having to create a specific type to hold them. In .NET 4.0, a set of Tuple classes has been introduced in the framework, which can be used as follows: private static Tuple<int, double> Tally(IEnumerable<double> values) { int count = 0; double sum = 0.0; foreach (var value in values) { count++; sum += value; } return Tuple.