Skip to content

IDE0251 does not take implicit conversions to Span<T> from InlineBuffer types #79384

@AlgorithmsAreCool

Description

@AlgorithmsAreCool

Related to #71500

Version Used:
10.0.100-preview.5.25277.114

Steps to Reproduce:

When using a range indexer on a instance of an inline buffer type, the analyzer for IDE0251 doesn't track the usage of a writable reference in the method body and suggests the method should be marked readonly. The compiler however does correctly tract the reference usage and disputes the reccomendation

public struct Example
{
    private Buffer _buffer;

    public void Set(int index, int value)//IDE0251: Member can be made 'readonly'
    {
        var bufferSpan = _buffer[..0];

        bufferSpan[0] = value;
    }

    public readonly int SetWithReadonly(int index, int value)
    {
        var bufferSpan = _buffer[..0];

        //CS8331: Cannot assign to property 'this' or use it as the right hand side 
        // of a ref assignment because it is a readonly variable
        bufferSpan[0] = value;
        return 1; // Return the number of elements set
    }

    public int SetWithExplicitSpanCast(int index, int value)//No diagnostic
    {
        Span<int> bufferSpan = _buffer;

        bufferSpan[0] = value;
        return 1; // Return the number of elements set
    }

    public int SetWithImplicitConversionToExplicitSpanVariable(int index, int value)//IDE0251: Member can be made 'readonly'
    {
        Span<int> bufferSpan = _buffer[..0];

        bufferSpan[0] = value;
        return 1; // Return the number of elements set
    }



    //This also effects indexer setters
    public int this[int index]
    {
        set //Member can be made 'readonly'IDE0251
        {
            var bufferSpan = _buffer[..0];
            bufferSpan[0] = value; // Set the first element
        }
    }
}

[InlineArray(1)]
public struct Buffer
{
    private int _element0;
}

Diagnostic Id:

IDE0251

Expected Behavior:

No IDE0251

Actual Behavior:
IDE0251

Metadata

Metadata

Labels

Area-Compilershelp wantedThe issue is "up for grabs" - add a comment if you are interested in working on it

Type

Projects

Status

Completed

Relationships

None yet

Development

No branches or pull requests

Issue actions