views:

82

answers:

3
+1  Q: 

Custom Data Types

Hello, quick question:

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!

+3  A: 

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
+5  A: 

Use an enum:

  enum ColorSortQualities
  {
       None,
       DistinguishColor,
       DistinguishNumberOfColors,
       DistinguishColorPattern
  };
n535
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
Well, actually i don't know whether it is considered to be a good or bad practice, so thanks.
n535
After reading http://stackoverflow.com/questions/746812/best-practices-for-using-and-persisting-enums things seem clear, thank you once again.
n535
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
+4  A: 

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

Mark Byers
Perfect! Exactly what I was looking for. Thanks again
Tinkerer_CardTracker