MrFox
MrFox

Reputation: 5126

modify variable for both getter and setter

The following property just begs for a value being calculated once for both getter and setter

So instead of:

public bool this[int x, int y]
{
    get
    {
        return this[x * this.width + y];
    }
    set
    {
        this[x * this.width + y] = value;
    }
}

It be better if we could do this:

public bool this[int x, int y]
{
    int index = x * this.width + y;

    get
    {
        return this[index];
    }
    set
    {
        this[index] = value;
    }
}

In this case it's not such a big deal and an inline method could be used. But as a principle, is there a way?

Upvotes: 1

Views: 1315

Answers (3)

Honza Brestan
Honza Brestan

Reputation: 10957

The get and set property accessors are actually compiled to two independent methods. If you need common code, you'll have to do it the same way as with any two different methods - by introducing a third method, possibly a static one.

private static CalculateIndex(int x, int width, int y)
{
    return x * width + y;
}

public bool this[int x, int y]
{
    get
    {
        return this[CalculateIndex(x, this.width, y)];
    }
    set
    }
        this[CalculateIndex(x, this.width, y)] = value;
    }
}

You cannot simply set a variable in this case so that it'd be common to the indexer's accessors, but if the calculation is really demanding, you may use some kind of caching, in which case you would access the cache in your accessors (just like the index variable in your example). The problem with this is that a cache is really heavyweight solution, you would have to handle checking if a value is cached, calculating it if it isn't and in some cases also removing it from the cache (especially to avoid memory leaks).

Upvotes: 5

Guvante
Guvante

Reputation: 19221

If you don't want to do the calculation twice, then add a helper method.

int GetOffset(int x, int y)
{
    return x + this.width * y;
}

public bool this[int x, int y]
{
    get
    {
        return this[GetOffset(x, y)];
    }
    set
    {
        this[GetOffset(x, y)] = value;
    }
}

Upvotes: 1

Tigran
Tigran

Reputation: 62265

May be something like this:

public bool this[int x, int y]
{    
    get
    {
        var index= x * this.width + y; //CALCULATE INDEX ON GET
        return this[index];
    }
    set
    {
        var index= x * this.width + y;//CALCULATE INDEX ON SET
        this[index] = value;
    }
}

Upvotes: -1

Related Questions