Why only static operators and nonstatic indexers? 
Author Message
 Why only static operators and nonstatic indexers?

CSharp reference says that operators have to be static but
indexers can't be static.
But what can you do if you really what to use an indexer in an operator?
(Of course I can define a static _get and _set method and call them inside
the indexer - but thats not very nice and has some runtime overhead)

class A {
    public static A operator + (A a1, A a2) {
        ..... use _get and _set here instead the indexer directly
    }

    public int A[int i] {
        get {
           return _get(i);
        }
        set {
           _set(i, value);
        }
    }

    private static int _get(int i) {
        return 0;
    }
    private static void _set(int i, int val) {
    }

Quote:
}

Any suggestion?


Tue, 23 Nov 2004 02:21:44 GMT  
 Why only static operators and nonstatic indexers?
Jrgen,

Quote:
> CSharp reference says that operators have to be static but
> indexers can't be static.
> But what can you do if you really what to use an indexer in an operator?
> (Of course I can define a static _get and _set method and call them inside
> the indexer - but thats not very nice and has some runtime overhead)

> class A {
>     public static A operator + (A a1, A a2) {
>         ..... use _get and _set here instead the indexer directly
>     }

Sure you can use the indexer directly. After all, a1 anda2 are both
_instances_ and you can invoke any instnace method on them (as well as the
result A instance).

You have to remember that in C#, operators usually have copy semantics, that
is, they return a _new_ instance! (unlike in C++, where you usually do a
"return *this;").

--
Tomas Restrepo



Tue, 23 Nov 2004 02:49:29 GMT  
 Why only static operators and nonstatic indexers?
Hi Juergen.

You are correct. The operator itself must be public and static. However,
the type (struct or class) that holds the operator can be instantiated.



Wed, 24 Nov 2004 03:50:20 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. Are static indexers possible?

2. Why there is no static destructor corresponding to static constructor

3. An object reference is required for the nonstatic field, method, or property

4. call from nested class method nonstatic of the class containing

5. static void* operator new

6. error LNK2005: "public: static void __stdcall CObject::operator delete help

7. error LNK2005: "public: static void __stdcall CObject::operator delete help

8. Why do unary operators promote the operand ?

9. Why can't operator delete be overloaded?

10. Why use address-of operator (&)??

11. Why isn't there a ->= operator?

12. why just a power operator?

 

 
Powered by phpBB® Forum Software