What is | in C# here? - c#

In the following code block there are a few bitwise OR's. I've never used them before so I was trying to understand what the code block meant.
Document doc = new Document("CleanupOptions.docx");
doc.MailMerge.CleanupOptions = MailMergeCleanupOptions.RemoveUnusedRegions |
MailMergeCleanupOptions.RemoveUnusedFields |
MailMergeCleanupOptions.RemoveContainingFields;
doc.MailMerge.ExecuteWithRegions(dataSet);
So in that block above, if I used doc.MailMerge.CleanupOptions, how would I pick any of the statements that the CleanupOptions are equal to? Or are they all combined?

They are all combined. An enum can be marked with the [FlagsAttribute] which allows combination of values:
https://msdn.microsoft.com/en-us/library/system.flagsattribute(v=vs.110).aspx

The MailMergeCleanupOptions is an enum with the FlagsAttribute specified. This allows you to do bit-wise ors to join the values into a collection. Normally the values are powers of two or a combination of flags.

Related

Why is my enum comparison not finding the proper value?

I am trying to find a specific Enum from a list of objects. Here is the code:
foreach (IEquipment eq in EntityEquipmentList)
{
if (eq.capability == capabilityEnum.Jam)
{
Console.WriteLine(eq.ToString())
}
}
Just to be clear, EntityEquipmentList is a List of IEquipment objects and I am trying to find the one that has "Jam" as it's capability. As you can see in the "if" statement, I want the capability of "Jam".
Enum in question:
Radar = 1
Jam = 2
Radio = 4
LowFreq = 8
HighFreq = 16
And to be clear, I am 100% certain that there is a piece of Equipment in the list with the Capability of Jam.
Note that the values in your capabilities enum are "powers of two" (1, 2, 4, 8, ... instead of 1, 2, 3, 4, ...). This is usually done for flag enums, where an enum value can be a combination of different defined values. For example, an equipment could have the capability of Jammer as well as Radar.
Well, now Jammer + Radar (or, to be precise: Jammer | Radar, using bitwise OR) is not equal to Jammer, which is why your comparison fails. You can fix this by using HasFlag instead of Equals:
if (equipmentCapability.HasFlag(CapabilityEnum.Jammer)) { ... }
In addition, you should add the Flags attribute to your enum. This
documents the fact that these enum values can be combined, and also
causes equipmentCapability.ToString() to output Jammer, Radar instead of the numerical value.

If statement not working as expected on combined enum value

This is a quirky one.
I have the following code...
foreach (IScanTicket ticket in this) {
if (ticket.Status == TicketStatus.Created || ticket.Status == (TicketStatus.Transfered | TicketStatus.Created))
return ticket;
}
}
When I run this, where the status is Created|Transferred, the if statement seems to fail (not do what it's suppose to).
The interesting thing is that if I debug and step through the code and watch the statement, it always returns TRUE in my debugger, yet it fails to enter the block when I step through the code.
Why would the debugger show that the statement is true, yet continue like it's not? It's like what the debugger is telling me fibs.
Has anyone ever experienced this?
P.S. I'm using Xamarin studio 5.9.7
Too long for a comment:
Actually, the [Flags] attribute does not change an enum's semantics at all, it's most popularly used by the ToString method to emit a series of names rather than a number for a combined value.
Let's say your enum was declared like this (without the Flags attribute):
enum TicketStatus
{
Created = 1,
Transferred = 2,
Sold = 4
}
You could still combine different members and do any arithmetic that applies to a Flags enum:
TicketStatus status = TicketStatus.Created | TicketStatus.Transferred;
However, the following will print 3:
Console.WriteLine(status);
But if you add the [Flags] attribute, it will print Created, Transferred.
Also, it's important to note that by TicketStatus.Created | TicketStatus.Transferred you're really doing a bitwise OR on the underlying integer value, notice how in our example that the assigned values are unambiguously combinable:
Created : 0001
Transferred: 0010
Sold: 0100
Therefore a value of 3 can be unambiguously determined as a combination of Created and Transferred. However if we had this:
enum TicketStatus
{
Created = 1, // 0001
Transferred = 2, // 0010
Sold = 3, // 0011
}
As it is obvious by the binary representations, combining values and checking against members is problematic as combined members could be ambiguous. e.g. what is status here?
status = TicketStatus.Created | TicketStatus.Transferred;
Is it Created, Transferred or is it really Sold? However, the compiler won't complain if you try to do it, which could lead to hard to track down bugs like yours, where some check is not working as you expect it to, so it's on you to ensure the definition is sane for bitwise mixing and comparing.
On a related note, since your if statement is really only checking if the ticket has a Created status, regardless of being combined with other members, here's a better way to check for that (.NET >= 4):
status.HasFlag(TicketStatus.Created)
or (.NET <4):
(status & TicketStatus.Created) != 0
As to why your enum did not work as expected, it is almost certainly because you did not explicitly specify unambigously bitwise combinable values to its members (typically powers of two).
Thanks to #MarcinJuraszek and #YeldarKurmangaliyev.
Seems the [Flags] attribute wasn't set on the enum as I originally thought. Adding this attribute now makes the enum work in either combination.
So it seems that not having this attribute effects the order of joined enum values.

Irony: How to give KeyTerm precedence over variable?

Relevant chunk of Irony grammar:
var VARIABLE = new RegexBasedTerminal("variable", #"(?-i)\$?\w+");
variable.Rule = VARIABLE;
tag_blk.Rule = html_tag_kw + attr_args_opt + block;
term_simple.Rule = NUMBER | STRING | variable | boolean | "null" | term_list;
term.Rule = term_simple | term_filter;
block.Rule = statement_list | statement | ";";
statement.Rule = tag_blk | directive_blk | term;
The problem is that both a "tag" and a "variable" can appear in the same place. I want my parser to prefer the tag over the variable, but it always prefers the variable. How can I change that?
I've tried changing tag_blk.Rule to PreferShiftHere() + html_tag_kw + attr_args_opt + block; and ImplyPrecedenceHere(-100) + html_tag_kw + attr_args_opt + block; but it doesn't help any. The parser doesn't even complain of an ambiguity.
Try changing the order of 'tag_blk.Rule' and 'variable.Rule' as tokenisers usually go after first match, and variable is first in your list.
You can increase the Priority of the tag_blk Terminal or decrease the one of variable whichever suits your purpose. Terminal class has a Priority field defaulting to 0. According to the comment right above it
// Priority is used when more than one terminal may match the input char.
// It determines the order in which terminals will try to match input for a given char in the input.
// For a given input char the scanner uses the hash table to look up the collection of terminals that may match this input symbol.
// It is the order in this collection that is determined by Priority property - the higher the priority,
// the earlier the terminal gets a chance to check the input.
Unfortunately I can't test this at the moment as the code fragment provided needs work and lots of assumptions to be made compilable. But from the description above this should be the one you are looking for. Hope it helps someone -even 10 years after the question aired.

Is there a C# unit test framework that supports arbitrary expressions rather than a limited set of adhoc methods?

Basically NUnit, xUnit, MbUnit, MsTest and the like have methods similar to the following:
Assert.IsGreater(a,b)
//or, a little more discoverable
Assert.That(a, Is.GreaterThan(b))
However, there are a limited number of such comparison operators built-in; and they duplicate the languages operators needlessly. When I want anything even slightly complex, such as...
Assert.That(a.SequenceEquals(b))
I'm often either left digging through the manual to find the equivalent of the expression in NUnit-speak, or am forced to fall-back to plain boolean assertions with less helpful error messages.
C#, however, integrates well with arbitrary Expressions - so it should be possible to have a method with the following signature:
void That(Expression<Func<bool>> expr);
Such a method could be used to both execute the test (i.e. validate the assertion) and to also provide less-opaque diagnostics in case of test failure; after all, an expression can be rendered to pseudo-code to indicate which expression failed; and with some effort, you could even evaluate failing expressions intelligently to give some clue of the value of subexpressions.
For example:
Assert.That(()=> a == b);//could inspect expression and print a and b
Assert.That(()=> a < b && b < c);
//could mention the values of "a<b" and "b<c" and/or list the values of a, b, and c.
At a minimum, it would make the use of a parallel language for expressions unnecessary, and in some cases it might make failure messages more useful.
Does such a thing exist?
Edit: After trying (and liking!) Power Assert, I ended up reimplementing it to address several limitations. My variant of this is published as ExpressionToCode; see my answer below for a list of improvements.
Check out the PowerAssert library (example output below):
PAssert.IsTrue(() => x + 5 == d.Month * y);
System.Exception : IsTrue failed, expression was:
x + 5 == d.Month * y
| | | | | | |
| | | | | | 6
| | | | | 18
| | | | 3
| | | 01/03/2010 00:00:00
| | False
| 16
11
http://powerassert.codeplex.com/
http://satisfyr.codeplex.com/
Uses lambda expressions exactly like you described. You don't even take on a binary dependency, just add a single source file corresponding to your unit test framework.
There is actually a very good reason that NUnit provides it's own DSL rather than using normal C# expressions. It's that NUnit is supposed to work with any .NET language
using the same syntax. That's not to say we can't have lambdas, just that we won't ever
rely exclusively on any particular language feature.
Many of the ideas given will work and many of the third-party software solutions could be incorporated into NUnit, provided that their authors want to offer them. Of course, lots of folks prefer to keep their solutions separate and that's OK too. But talk to your favorite authors if you want them to collaborate more closely with NUnit.
In NUnit 2.5, you can use PredicateConstraint, which takes a lambda as its argument. However, the syntax is a bit limiting. The Matches keyword will work in the middle of an expression, so you can write...
Assert.That(someActual, Not.Matches( someLambda );
but doing it without the Not requires...
Assert.That(someActual, new PredicateConstraint( someLambda ));
And, of course, neither of these is as clean as the suggested syntax.
Everyone interested in this issue is welcome to join us on nunit-discuss where discussions about what should be in NUnit actually lead to action!
Charlie
Cone ( https://github.com/drunkcod/cone ) is a NUnit addin that works with 2.5.5 & 2.5.7 (other versions are only a recompile away) that gives you that capability along with a few other nifty features.
(Original Poster here)
I love PowerAssert.NET's simple syntax and messages, but the C# it produces has many issues. In particular, it doesn't support several expression features, and it doesn't add parentheses where required by operator precedence/associativity. After fixing a few bugs (and reporting them to the author) I found it'd be simpler to fix with a different approach, and to reimplement it from scratch.
The usage is similar:
PAssert.That(()=>
Enumerable.Range(0,1000).ToDictionary(i=>"n"+i)["n3"].ToString()
== (3.5).ToString()
);
Outputs:
PAssert.That failed for:
Enumerable.Range(0, 1000).ToDictionary(i => "n" + (object)i)["n3"].ToString() == 3.5.ToString()
| | | | | |
| | | | | "3.5"
| | | | false
| | | "3"
| | 3
| {[n0, 0], [n1, 1], [n2, 2], [n3, 3], [n4, 4], [n5, 5], [n6, 6], [n7, 7], [n8, 8], [n9, 9], ...}
{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ...}
Improvements over PowerAssert.NET:
Supports static field and property access
Supports more operators, such as logical and bitwise negation.
Recognizes C# indexer use (e.g. dict["mykey"]==3)
Adds parentheses where required by operator precedence and associativity (e.g. () => x - (a - b) + x * (a + b) is correctly regenerated)
Generates valid numeric and other constant literals including escapes and suffixes as appropriate for the expression type (e.g. 1m + (decimal)Math.Sqrt(1.41))
Supports C# syntactic sugar for object initializers, object member initializers, list initializers, extension methods, amongst other things.
Uses the same spacing rules Visual Studio does by default.
Supports nested Lambdas
Expands generic type instances into normal C#; e.g. Func<int, bool>
Supports several expression tree constructs not yet used by C# 4.0 embedded expressions.
The resultant project (with unit tests) is hosted in google code under the name ExpressionToCode - I hope it's useful to others.
No one that I know of, but I think this can be added to the upcoming NUnit 3 wishlist.
Some work to that end done in #TestEx http://sharptestex.codeplex.com/ is being thought for inclusion, but you can add a blueprint/issue for the more general approach you are asking.
https://blueprints.launchpad.net/nunit-3.0
https://bugs.launchpad.net/nunit-3.0
The Visual Studio 2010 unit test framework has a CollectionAssert class which is usefull.
It also provides an Assert.IsTrue(bool) for generic cases that you craft yourself but none that use expressions;

Question on how these 2 lines of code work

I am reading this article on how to work with AD via C#. Half way through the article, the below code is presented.
The user account properties are checkboxes. Does anyone have any idea what the below line of code will return for a checked checkbox? What if more than 1 checkbox is checked? I'd have thought a bool being returned would be more intuitive?
//Add this to the create account method
int val = (int)newUser.Properties["userAccountControl"].Value;
//newUser is DirectoryEntry object
Why do we do the logical or below? How does it work between an int and the second value (is that a byte?)
newUser.Properties["userAccountControl"].Value = val | 0x80000;
//ADS_UF_TRUSTED_FOR_DELEGATION
I know that sounds very naive...
Thanks
The userAccountControl property contains a two byte value in which each single bit has a significant meaning. If the bit is on, then some option is used - if it's not on, then the option is not present.
This is more compact and more space optimized than having a gazillion of booleans. Also, many "older" Win16 and Win32 API just simply work this way.
The bitwise "AND" operator is used to check for the presence of such a single bit:
if (newUser.Properties["userAccountControl"].Value & 0x400 == 0x400)
in this case, the 0x400 bit is set.
In order to actually set a bit, you use the bitwise "OR" operator:
newUser.Properties["userAccountControl"].Value = val | 0x800
This sets the "0x800" bit.
It's basic bit-wise boolean logic, really. A bit messy, indeed - but .NET has some help to make things a bit easier (check out the BitArray data type, for instance)
userAccountControl is a flag field, that's why they put it into an int.
See http://support.microsoft.com/kb/305144 for more information.
Based on the information that you are giving, I would guess that they are using a flags type system to indicate selected items. Each option has a specific value, and they are added up so you can get back which are selected.
This would be proved by the logical or that is used to see if a specific value is included.

Categories

Resources