Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

overloading [][] in c#

I'm building a tree-based data structure and overloaded [ ] so that I can say

node["key1", "key2", "key3"]

which returns the node whose parents 1, 2, and 3 levels above are the nodes with those keys. the nodes conceptually map to an array of data, so what I have now is this function:

node[keys...].SetValue(i, value)

which sets the i-th value in the node's data. what would be nice is if I could do this:

node[keys][i] = value

problem is, node[keys] returns a node, so the [i] indexing tries to get at another node. basically what I want to be able to do is overload "[ ][ ]" as an operator, which I can't.

is there any way to get at what I'm trying to do?

like image 763
toasteroven Avatar asked Jun 18 '26 17:06

toasteroven


1 Answers

Note: This answer talks about implementing something like obj[a][b][c]... that could work with variable number of brackets. It seems it's not exactly what the OP wanted.

You can't overload that directly. You should return an object with an indexer from the first indexer so that you could simulate this functionality.
It's a bit harder to simulate set but it's possible to do something like:

public class Node<T> {
    public Node<T> this[string key] {
        get { return GetChildNode(key); }
        set {
            if (value is DummyNode<T>) {
                GetChildNode(key).Value = value.Value;
            } else {
                // do something, ignore, throw exception, depending on the problem
            }
        }
    } 
    public static implicit operator T(Node<T> value) {
        return value.Value;
    }
    private class DummyNode<T> : Node<T> {
    }
    public static implicit operator Node<T>(T value) {
        return new DummyNode<T> { Value = value };
    }
    public T Value { get; set; }
}
like image 175
mmx Avatar answered Jun 21 '26 08:06

mmx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!