Enum or a class

A

AliR \(VC++ MVP\)

Hi Everyone,

I have writing a class that represents a object on a screen. The object has
normal things like X,Y, Width, Height, ZOrder, and it also has drawing
attributes and flags.

It has properties for setting and getting values from instance variables
that represent the above attributes of the class.
For the flags, which are bit values, I have 3 methods, one for setting, one
for removing and one for testing for the flags.

public abstract class ScreenItem
{
....
private uint flags;

public void SetFlags(uint flags)
{
this.flags |= flags;
}

public void RemoveFlags(uint flags)
{
this.flags &= ~flags;
}

public bool HasFlag(uint flag)
{
return (this.flags & flag) == flag;
}
....
}

now the question is should the flags be defined as an enum or another class
with const uints? What is the correct way of defining such a thing in C#

public abstract class ScreenItem
{
....
public enum FlagType { Selectable = 1, Movable = 2, Sizable = 4,
Editable = 8 };
....
}

or

public abstract class ScreenItem
{
....
public class FlagType
{
public const uint Selectable = 1;
public const uint Movable = 2;
public const uint Sizable = 4;
public const uint Editable = 8;
}
....
}

Thanks
AliR.
 
L

Larry Smith

See "FlagsAttribute" in MSDN. Here's one way to do it (very quickly written)

public abstract class ScreenItem
{
public bool Selectable
{
get
{
return GetFlag(Flags.Selectable);
}
set
{
SetFlag(Flags.Selectable, value);
}
}

private bool GetFlag(Flags flag)
{
Debug.Assert(flag != Flags.None);
return ((m_Flags & flag) == flag);
}

private void SetFlag(Flags flag, bool on)
{
Debug.Assert(flag != Flags.None);

if (on)
{
m_Flags |= flag;
}
else
{
m_Flags &= ~flag;
}
}

[Flags]
private enum Flags
{
None,
Selectable = 0x1
}

private Flags m_Flags;
}
 
J

jehugaleahsa

It should be implemented as an enum. Its location is really
immaterial, since they can technically be global.

I do agree that FlagsAttribute should be used.

I have written a few classes with an Add and Remove method for flags.
It is of course just a nicety for non-bit-sauvy individuals.

You may also consider making the enum private to the base class of
your widgets and simply having properties that turn the bits on and
off.

private enum FlagType { Selectable = 1, ... }

private FlagType flags;

public bool Selectable
{
get { return HasFlag(FlagType.Selectable); }
set
{
if (value)
{
SetFlag(FlagType.Selectable);
}
else
{
UnsetFlag(FlagType.Selectable);
}
}
}

Tada!
 

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