Cant access a sealed class 'this' indexer

D

Diego L.M.

Hi there.

I have 2 classes:

public sealed class Class1

{

private static ArrayList _al = new ArrayList();


static Class1()

{

}

public static int Add(Class2 c2)

{

_al.Add(c2);

return 1;

}

public Class2 this[int pos]

{

get {return (Class2)_al[pos];}

}

}

public class Class2

{

public int x;

public int y;

public Class2(int num1, int num2)

{

x = num1;

y = num2;

}

}

Basically, Class1 is a static class containing Class2 items.

I wanna access Class1 by index, but i get a CS0118.

Removing 'sealed' and making an instance of Class1 work perfectly.

I think the problem is in 'this' keyword, in the indexer accessor.

Here's the code:

private void Form1_Load(object sender, System.EventArgs e)

{

Class1.Add(new Class2(1,1));

Class1.Add(new Class2(2,2));

Class1.Add(new Class2(3,3));

int xx = Class1[1].x; // CS0118 'WindowsApplication3.Class1' denota 'clase',
cuando se esperaba 'variable'

}

Thanks in advance.
 
J

Jon Skeet [C# MVP]

Basically, Class1 is a static class containing Class2 items.

I wanna access Class1 by index, but i get a CS0118.

Indeed. You can't have static indexers in C#.
 
C

codymanix

Basically, Class1 is a static class containing Class2 items.
Indeed. You can't have static indexers in C#.


I noticed that the request for static indexers is very frequent this week :)
 

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