using
+ struct indexer emits CS1654, why?
#76904
-
Combining It seems to me that the compiler is behaving strangely. I'd like to know why. public static class MainClass
{
static void Main()
{
{
// manually Dispose - OK
var str = new RefStruct(stackalloc int[1]);
str[0] = 42;
str.Values[0] = 42;
str.Dispose();
}
{
// try-finally Dispose - OK
var str = new RefStruct(stackalloc int[1]);
try
{
str[0] = 42;
str.Values[0] = 42;
}
finally
{
str.Dispose();
}
}
{
// using - NG
using (var str = new RefStruct(stackalloc int[1]))
{
str[0] = 42; // error CS1654
str.Values[0] = 42; // valid
}
}
{
// using var - NG
using var str = new RefStruct(stackalloc int[1]);
str[0] = 42; // error CS1654
str.Values[0] = 42; // valid
}
}
}
ref struct RefStruct
{
public Span<int> Values;
public RefStruct(Span<int> buffer) => Values = buffer;
public int this[int index]
{
readonly get => Values[index];
set => Values[index] = value;
}
public void Dispose() { /* something */ }
}
|
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
A
Your code is attempting to modify the local variable as we define writing into an indexer on a struct as a mutation of it. If you want the compiler to view things differently, a change would have to happen to the language. Such changes start with a discussion at dotnet/csharplang. Thanks! |
Beta Was this translation helpful? Give feedback.
-
Thank you for your reply. But according to the link you provided,
But isn't it a contradiction that one passes and the other doesn't? Why is it that calling methods / writing to its property that inherently mutate internal state is permitted, so indexers fail? |
Beta Was this translation helpful? Give feedback.
-
{
using (var str = new RefStruct(stackalloc int[1]))
{
// What's the difference?
str[0] = 42; // error CS1654
str.Items(0) = 42; // valid
}
}
ref struct RefStruct
{
// ...
public ref int Items(int index) { return ref Values[index]; }
} |
Beta Was this translation helpful? Give feedback.
A
using
variable is defined to bereadonly
in the C# language specification. https://github.com/dotnet/csharpstandard/blob/standard-v6/standard/statements.md#1214-the-using-statementYour code is attempting to modify the local variable as we define writing into an indexer on a struct as a mutation of it. If you want the compiler to view things differently, a change would have to happen to the language. Such changes start with a discussion at dotnet/csharplang. Thanks!