operator question

K

Kimmo Laine

Hi

is there a way todo this in C#

class MyClass {
protected MyType1[] m_MyTypes1;
protected MyType2[] m_MyTypes2;

public MyClass() { . . . }

public MyType1 this[ int position ] {
get {
return m_MyTypes1[ position ];
}
}
public MyType2 this[ int position ] {
get {
return m_MyTypes2[ position ];
}
}
}

void Foo() {
MyClass m = new MyClass();
MyType1 m1 = m[ 1 ];
MyType2 m2 = m[ 1 ];
}

This won´t compile because there can´t be 2 this-operator overloads that
take the same arguments.

Any ideas how i can do this without using direct (SetMyType/GetMyType)
methods?


thx

Kimmo Laine
 
N

Nicholas Paldino [.NET/C# MVP]

Kimmo,

What you want to do is expose typed collections which will have indexers
that return the appropriate type. You can not produce an overload that
returns a different type (with the same parameter list).

I would recommend using a strongly typed collection, and storing those
in your class, exposing them through different properties which return
collection objects where the indexer will return the appropriate type.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top