Help creating a custom collection

  • Thread starter Thread starter DotNetNewbie
  • Start date Start date
D

DotNetNewbie

Hello,

I want to create a collection that will be accessed like the
following, that returns a Boolean value;


MyClass[userID].Attributes[SomeEnum.Value1];


Can someone help me with how I should design this cusotm collection?
 
Well, you really have two collections here.

The first (as represented by the instance MyClass) looks to be a
dictionary of some kind (although it doesn't have to be, this is just the
most applicable analogy) which has a key of whatever type userID is, and
returned an instance of whatever type exposes the Attributes property.

The second is another dictionary, which is keyed on the SomeEnum
enumeration, and returns bool. You can simply make the Attributes property
expose an IDictionary<SomeEnum, bool>.
 
If the attributes are genuinely keyed by an enum then you can save a
lot of time and space by properly using them as a bitmask.
Unfortunately C# does not support parameterised named indexers, soyou
can't write a bool Attributes[SomeEnum value] {get;set;}, but you can
just provide accessor methods. Of course, if you have more than 64
flags then you won't be able to use enum flags...

using System;
using System.Collections.Generic;

[Flags] // indicates bit-mask enum
enum SomeEnum {
None = 0, Foo = 1, Bar = 2, Fred = 4, Wilma = 8, Barney = 16
}
class SomeEntity {
SomeEnum attribs = SomeEnum.None;
public bool HasAttribute(SomeEnum attribute) {
return (attribs & attribute) == attribute;
}
public void SetAttribute(SomeEnum attribute, bool value) {
if (value){
attribs |= attribute;
} else {
attribs &= ~attribute;
}
}
}
class SomeCollection : Dictionary<int, SomeEntity>
{ // lazy - just for demo
}
static class Program {
static void Main() {
SomeCollection data = new SomeCollection();
data.Add(123, new SomeEntity());
bool test1 = data[123].HasAttribute(SomeEnum.Wilma);
data[123].SetAttribute(SomeEnum.Wilma, true);
bool test2 = data[123].HasAttribute(SomeEnum.Wilma);
data[123].SetAttribute(SomeEnum.Wilma, false);
bool test3 = data[123].HasAttribute(SomeEnum.Wilma);
bool test4 = data[123].HasAttribute(SomeEnum.Barney);
}
}
 

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

Back
Top