Skip to content

Add indexer to MatrixXxX es (preferably ref returning) #21705

Open
@BreyerW

Description

@BreyerW

I would like to be able to query any value of matrix using indexer

Like:

Matrix4x4 m=....

var firstRowColumn=m[0,0]; //equivalent to m.M11

This is mainly convenience, but become big one if one want to get matrix property "randomly" e.g. in for loop. In this case one must write pretty big if else block or switch. ref might be useful to be able to send matrixes to graphic libraries efficiently and conveniently.

Next use case is migrating between vector libraries that support indexers (like OpenTk) Note: ref returning indexer shouldnt be problem there because omitting ref when calling means automatic dereference so in theory one could just change using and recomplie without problems (assuming no issues with world coordinates etc.)

Since ref and out alternative methods got postponed, i think patch with them is perfect to include ref indexers as well unless you want to backport them to ealier versions of c# than 7

EDIT: If you decide to implement ref indexer without changing internal representation, i think it could be implemented using Unsafe.Add. Something along these lines:

public ref float this[int row,int col]{
    get{

if(row<0 || row>3 || col<0 || col>3) throw new IndexOutOfRangeException();

             var index=0;
             if(row is 1)
                      index=4;
             else if(row is 2)
                      index=8;
             else if(row is 3)
                      index=12;

             index+=col;
             return ref Unsafe.Add<float>(ref this.M11,index );
     }
}

EDIT 2: With spans available, you could implement indexers for retrieving only row or only column (return 4-elements span which is constructed using DangerousCreate(this, ref this.MdesiredRow0, 4), Column is more tricky and probably would be implemented as tuple or float[4] since column arent layed out in continguous blocks, unless you add 'jumping' every X elements support to spans. Or just return span over whole matrix and force users to deal with 'jumping')

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.NumericsblockedIssue/PR is blocked on something - see comments

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions