1

I'd like to create some custom data types, but I don't think I'm asking the right question(s).

There are "compound Boolean" values used throughout .NET, and I want to design some of my own. I've been using a series of Boolean variables, which works, but just isn't the same.

Examples from .NET include: Color.Black Alignment.Centered [fontProperties].Bold* *I forget the actual name, but you get the idea

I want to make something like this:

ColorSortQualities

  • None
  • DistinguishColor
  • DistinguishNumberOfColors
  • DistinguishColorPattern

Once that's been declared, I could do this: if(searchOptions.ColorSortQualities == DistinguishColor) [do stuff]

What is this called?

Thanks!

Daniel DiPaolo
  • 55,313
  • 14
  • 116
  • 115
Tinkerer_CardTracker
  • 3,397
  • 3
  • 18
  • 21
  • 1
    Is it possible to have both 'DistinguishColor' and 'DistinguishColorPattern' at the same time, or are they mutually exclusive? – Mark Byers Apr 10 '10 at 19:37

3 Answers3

5

Use an enum:

  enum ColorSortQualities
  {
       None,
       DistinguishColor,
       DistinguishNumberOfColors,
       DistinguishColorPattern
  };
n535
  • 4,983
  • 4
  • 23
  • 28
  • 1
    unecessarily explicitly declaring the type of an enum as other than int32 is a bad move in my opinion. Are you trying to save a few bytes on a static type? – Sky Sanders Apr 10 '10 at 19:30
  • Well, actually i don't know whether it is considered to be a good or bad practice, so thanks. – n535 Apr 10 '10 at 19:32
  • After reading http://stackoverflow.com/questions/746812/best-practices-for-using-and-persisting-enums things seem clear, thank you once again. – n535 Apr 10 '10 at 19:39
  • Virtually every enum in the CLR is the default int32. Explicit declaration otherwise, unless the enum is being repurposed in an edge case, for use in an api call requiring a byte for instance, just adds noise. I am measuring best practice from what I have seen, that's all. – Sky Sanders Apr 10 '10 at 19:39
4

It's called an enumeration and in C# you use the keyword enum.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
3

I think you want a enumeration with the [Flags] attribute.

[Flags]
enum ColorSortQualities
{
    None = 0x0,
    DistinguishColor = 0x1,
    DistinguishNumberOfColors = 0x2,
    DistinguishColorPattern = 0x4
}

This will let the caller specify any combination of those, each of which will be implemented as a bit flag. Note that this will allow 32 options, because int is a 32-bit quantity.

Your condition code would look like:

if((searchOptions & ColorSortQualities.DistinguishColor) == ColorSortQualities.DistinguishColor)

If that isn't what you mean by "series of Boolean variables", please clarify.

Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539