Patrik Fröhler
Patrik Fröhler

Reputation: 1291

Access operator / accessor in C# class

If I create a class in C# example a Custom Matrix4 class is it possible to write the class in a way that allow me to access it without having to access explicitly the member variable.

Example of a simple Matrix4 class:

class Matrix4
{
    private double[,] _m = new double[4, 4] { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
    public double[,] m
    {
        get { return (_m); }
        set { _m = value; }
    }
}

and to access the actual 2D array aka the matrix I would have to write m4.m[1, 1] is it possible to have it where you don't have to write the .m so it would just be m4[1, 1], it not super importation but it would be nice and it possible in C++ so thought it might be possible in C# as well but haven't been able to find anything about it.

Current how to access it:

Matrix4 m4 = new Matrix4();
Debug.Log(m4.m[1, 1]);

How I would like it to be:

Matrix4 m4 = new Matrix4();
Debug.Log(m4[1, 1]);

Upvotes: 0

Views: 103

Answers (2)

Xavier
Xavier

Reputation: 106

Use an indexer (https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/)

class Matrix4
{
    private double[,] _m = new double[4, 4] { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
    public double this[int i,int j]
    {
        get { return (_m[i,j]); }
        set { _m[i,j] = value; }
    }
}
var m4 = new Matrix4();
// m4[1,1] == 1

Upvotes: 0

Patrik Fröhler
Patrik Fröhler

Reputation: 1291

Apparently its called indexer in C# thanks to @itsme86 comment pointing that out.

Here is how to do it with the matrix example:

 class Matrix4
    {
        private double[,] _m = new double[4, 4] { { 1, 0, 0, 0 }, { 0, 1, 0, 0 }, { 0, 0, 1, 0 }, { 0, 0, 0, 1 } };
        public double this[int x, int y]
        {
            get { return (_m[x, y]); }
            set { _m[x, y] = value; }
        }
    }

and to access it:

Matrix4 m4 = new Matrix4();
Debug.Log(m4[1, 1]);

Upvotes: 1

Related Questions