Information Technology Reference
In-Depth Information
need to be accessible. But, when you are creating an enum , you cannot force
other developers to abide by those rules. The best you can do is to create
enum types where the 0 bit pattern is valid, even if that isn't a perfect
abstraction.
Before leaving enums to discuss other value types, you need to understand
a few special rules for enums used as flags. enums that use the Flags attrib-
ute should always set the None value to 0:
[ Flags ]
public enum Styles
{
None = 0 ,
Flat = 1 ,
Sunken = 2 ,
Raised = 4 ,
}
Many developers use flags enumerations with the bitwise AND operator.
0 values cause serious problems with bitflags. The following test will never
work if Flat has the value of 0:
if ((flag & Styles .Flat) != 0 ) // Never true if Flat == 0.
DoFlatThings();
If you use Flags, ensure that 0 is valid and that it means “the absence of all
flags.”
Another common initialization problem involves value types that contain
references. Strings are a common example:
public struct LogMessage
{
private int ErrLevel;
private string msg;
}
LogMessage MyMessage = new LogMessage();
MyMessage contains a null reference in its msg field. There is no way to
force a different initialization, but you can localize the problem using prop-
erties. You created a property to export the value of msg to all your clients.
Add logic to that property to return the empty string instead of null :
 
Search WWH ::




Custom Search