Multiple Indexers

A

AliR \(VC++ MVP\)

Hi Everyone,

I have a class that has two instance variables that are Dictionaries. Now
in addition to having properties to access these dicitionaries, I wanted to
have a properties. But it seems like there can only be one in the class. Am
I missing something?

public class LSItem
{
enum DrawingAttributes { PenWidth, PenColor, FillColor,
TransformA..... };
private Dictionary<DrawingAttributes, float> attributes;
private Dictionary<DrawingAttributes, float> otherattributes;

//I know that I can have an index like so
public float this[DrawingAttributes i]
{
get { return attributes; }
}

//I would have thought that I could do this:
public float DrawingAttribute[DrawingAttributes i]
{
get {...}
set {...}
}

public float OtherAttribute[DrawingAttributes i]
{
get {...}
set {...}
}
}

That way I could have
LSItem item = new LSItem();
float penWidth = item.DrawingAttribute[LSItem.DrawingAttributes.PenWidth];

AliR.
 
A

AliR \(VC++ MVP\)

Thanks Pete. I appreciate you input.

AliR.


Peter Duniho said:
When you write "I wanted to have a properties", do you actually mean you
want indexers, one for each dictionary?

If so, then the basic answer is no, you can't do that, not in C# (my
recollection is that the CLR supports it and that VB.NET has a syntax that
allows it). The closest you can come is to overload the indexer in your
class, using one for one dictionary and one for the other. But that would
require that each dictionary use an index of different type, which doesn't
appear to be the case in your situation (though, I suppose you could force
it by creating two special indexing types for the purpose).

Alternatively, since you seem to be indexing your dictionaries by a custom
enumeration, presumably where values associated with any given key will
only ever be found in one or the other dictionary, you could have a single
indexer that examines the index first and selects the appropriate
dictionary based on the key (for example, define your keys so that all for
each dictionary fall into a particular range, or have a particular bit set
or something like that).

All that said, I think you should avoid using an indexer in a class unless
that class is really itself semantically a collection. If it's not, then
an explicit method for the purpose would be much better IMHO. For
example, instead of a "DrawingAttribute" and "OtherAttribute" property
that you index, just have a "GetDrawingAttribute()" and
"GetOtherAttribute()" method. This makes it more clear that the "LSItem"
class isn't really just a collection of these attributes, but instead is
an object that _has_ attributes of different classifications.

Pete
 

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