C
C#17mo ago
Loup&Snoop

❔ Offset property for array

Suppose I have an array: public int[,] paddedArray = new int[width + 6, height + 6]; I want to make a property that accesses values offset, to get something like unpaddedArray[x,y]: get gives paddedArray[x+3,y+3], and set will set paddedArray[x+3,y+3]; Would anyone know how to define this?
4 Replies
Loup&Snoop
Loup&SnoopOP17mo ago
I would like to do this in a really lightweight way, because the alternative is just to put a const everywhere, and that would just be obnoxious I could do something like :
private int[,] paddedIntGrid;
public int GetInt(int x, int y) { return paddedIntGrid[x + PADDING, y + PADDING]; }
public void SetInt(int x, int y, int myInt) { paddedIntGrid[x + PADDING, y + PADDING] = myInt; }
private int[,] paddedIntGrid;
public int GetInt(int x, int y) { return paddedIntGrid[x + PADDING, y + PADDING]; }
public void SetInt(int x, int y, int myInt) { paddedIntGrid[x + PADDING, y + PADDING] = myInt; }
But I'd like to know if there is a simpler way to make the syntax more like just accessing the array itself.
Vi Ness
Vi Ness17mo ago
You can use indexers to make something like this
internal class PaddedMatrix
{
private int[,] _matrix;
private int _padding;
private int _halfPad;

public PaddedMatrix(int size, int padding)
{
_padding = padding;
_halfPad = _padding / 2;
_matrix = new int[size+padding, size+padding];
}

public int this[int x, int y]
{
get => _matrix[x + _halfPad, y + _halfPad];
set => _matrix[x + _halfPad, y + _halfPad] = value;
}
}
internal class PaddedMatrix
{
private int[,] _matrix;
private int _padding;
private int _halfPad;

public PaddedMatrix(int size, int padding)
{
_padding = padding;
_halfPad = _padding / 2;
_matrix = new int[size+padding, size+padding];
}

public int this[int x, int y]
{
get => _matrix[x + _halfPad, y + _halfPad];
set => _matrix[x + _halfPad, y + _halfPad] = value;
}
}
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/indexers/using-indexers
Using Indexers - C# Programming Guide
Learn how to declare and use an indexer for a class, struct, or interface in C#. This article includes example code.
Loup&Snoop
Loup&SnoopOP17mo ago
thank you. that is useful I tried to avoid a custom mini class, but I think it is worth it
Accord
Accord17mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.
Want results from more Discord servers?
Add your server