Roslyn: Please allow ref on foreach variable in case of an array

Created on 30 Dec 2016  路  11Comments  路  Source: dotnet/roslyn

foreach(ref var item in array)
{
}

->

for(int i = 0; i < array.Length; ++i)
{
  ref var item = ref array[i];
}
0 - Backlog Area-Language Design Language-C#

Most helpful comment

In order to make that readonly we'd need to support the notion of readonly ref. That is actually something we're looking into seriously for the next version of C#.

All 11 comments

This is genius.

I assume that item would be readonly?

@HaloFour,

That seems extremely unlikely, given the team's resistance to making anything read-only by default.

In fact, the only use-case I can think of for this would be:
cs foreach(ref var item in array) { item = some new value; }
which would mean it would be useless if read-only. Unless I'm missing the obvious as usual... 馃槉

@jnm2 It is actually C++. :)

@HaloFour Since this would be only allowed for arrays, it is totally safe to be assigned. I think that's the case for readonly ref which doesn't exist yet.

@DavidArno It is currently readonly for non-ref case, which is a good thing. But in this case we explicitly declared it as ref so I don't think that would come as a surprise. Also, when it's ref it is already guarded against closure capture etc. readonly ref would not be useless; it avoids copying but still readonly.

@DavidArno

That seems extremely unlikely, given the team's resistance to making anything read-only by default.

Except for foreach iterator variables, which have always been readonly. That's explicitly why I mentioned it.

In order to make that readonly we'd need to support the notion of readonly ref. That is actually something we're looking into seriously for the next version of C#.

@jaredpar You mean like the next major release?

@eyalsk it will not be a part of C# 7.0. But it is a candidate for coming out in a point release / VS update.

@jaredpar Thank you very much.

@alrz

@jnm2 It is actually C++. :)

馃槅 馃槅
It won't be until we have
C# foreach(ref ref var item in array) { ... }
pure gold

Was this page helpful?
0 / 5 - 0 ratings

Related issues

stephentoub picture stephentoub  路  259Comments

ghost picture ghost  路  229Comments

mattwar picture mattwar  路  190Comments

stephentoub picture stephentoub  路  167Comments

mgravell picture mgravell  路  119Comments