Search code examples
c#arraysgettersetter

How to wrap around values (using `mod`) when using get/set for array values?


NOTICE: I do not want do wrap the index of the array, in fact, I already did that. I also want to wrap the individual values of the array when they are set.

I am trying to get array values to automatically wrap around without using a for loop to do it, because I have a fairly large array (uint16 limit).

I was trying to use a get/set and use a simple wrap code if it is above the max or below the minimum.

Is there any way I can do this?

What I want:

MyArray[0] = 5

//MyArray's max is 3, and minimum is 0

Outcome: MyArray[0] = 2


The problem is not looping around indices, but instead to have the values reduced to a limited range.

I've seen how to implement indexer - like Example of Indexer and how to clamp value - Where can I find the "clamp" function in .NET? (some even were suggested as duplicates).


Solution

  • this help?

    using System;
    public class ModArray
    {
        int [] _array;
        int _mod;
        public ModArray(int size, int mod){
            _array = new int[size];
            _mod = mod;
        }
        public int this[int index]
        {
            get => _array[index];
            set => _array[index] = value % _mod;
        }
    }
    public class Test
    {
        public static void Main()
        {
            var ma = new ModArray(10,3);
            ma[0] = 5;
            Console.WriteLine(ma[0]);
            }
    }