1. What is the purpose of the |= operator here?
|= is a special C# assignment operator that combines assignment (=) with a bitwise-OR (|).
You may be more familiar with the more common +=,
sum += item.Value;
which is equivalent to,
sum = sum + item.Value;
Similarly,
codeMethod.Attributes |= MemberAttributes.Static;
is equivalent to,
codeMethod.Attributes = codeMethod.Attributes | MemberAttributes.Static;
which says the Attributes are the same as they are originally, but the Static
flag is turned on (if it isn't already on).
2. I'd like to make it static AND public. It appears to only allow you to
do one ... if you do both in a row, the second prevails. The default
behavior is private and an instance method. Is there a workaround?
Attributes is a [Flags] enumeration. If you're familiar with C programming, you
may have encountered enums that were used to create "bitmasks" such as,
enum MyFlags {
XMIT_CHAR = 1,
RECV_CHAR = 2,
CARRIER = 4
};
and in this case you could have an int variable that could contain none-, one-,
two- or all three- of these binary bit flags. You would turn ON a flag by using
a bitwise-OR operation, or you would turn OFF a flag by using a bitwise AND
operation. For example (this is in C pseudocode),
/* auxStatReg is 5, it has bits 0 and 2 turned ON. */
int auxStatReg = XMIT_CHAR | CARRIER;
/* auxStatReg is 4, bit 0 has been turned OFF. */
auxStatReg = auxStatReg & CARRIER;
/* auxStatReg is tested to see whether bit 2 is turned ON. */
if ( ( auxStatReg & CARRIER ) == CARRIER )
/* we have carrier. */
else
/* no carrier. */
These operations continue to be used in C#, in fact they've been improved and
enum declarations that have a [FlagsAttribute( )] applied to them automatically
support these sorts of operations with strong compile-time type checking (and
meaningful identifier names when debugging in the IDE).
In this case, Attributes is of type MemberAttributes which is a [Flags] enum.
That means you can turn on multiple flags, but working with them means you
need to be familiar with using the bitwise-OR and -AND operations.
CodeMemberMethod method = new CodeMemberMethod();
method.Name = "MyMethod";
method.Attributes = MemberAttributes.Static;
method.Attributes = MemberAttributes.Public; //This one overwrites the
other!!
You can use the bitwise-OR operator, |, to turn on both flags.
// Makes the Attributes Static and Public (overwrites previous Final, Private
// flag selections).
//
method.Atributes = MemberAttributes.Static | MemberAttributes.Public;
If you're familiar with Set Theory, think of OR as performing a Union, and
think of AND as performing an Intersection.
Derek Harmon