Line []. Count () gives strange result
I am debugging some code and came across this strange scenario. The method takes a variable String[]
, and first checks if this variable is equal ...
protected override CommandResult OnExecute(DateTime closeOfBusinessDate,
string[] verbs)
{
if (verbs == null)
{
throw new ArgumentNullException("verbs");
}
We pass this string, and the next one will check it to make sure that the variable has at most one value ...
if (verbs.Count() > 1)
{
throw new ArgumentException("Only single verb supported.", "verbs");
}
This is pretty basic stuff, but while debugging I see this result ...
As you can see it Count()
has a value of 1 , but the validation still evaluates to true for if (verbs.Count() > 1)
, can that explain this? I may have missed something obvious.
EDIT : added output
You can see the value 1 in the output window .
source to share
Consider the following code:
static void Example()
{
var verbs = new string[] { null, null };
checkBerbs(verbs);
}
static void checkVerbs(string[] verbs)
{
if (verbs.Count() > 1)
{
mutateArray(ref verbs); //this would run another thread --> race condition
throw new ArgumentException();
}
}
private static void mutateArray(ref string[] verbs)
{
verbs = new string[] { null };
}
This is a possible scenario. Without knowing the full extent of your code, I'm not sure if this is possible. Obviously this mutateArray
will run on a different thread and you will have a race condition. Maybe blocking verbs
can let you know that this is a concurrency issue.
source to share
If the code actually calls the extension method Enumerable.Count
and no trickery exists, the problem is that you are assuming the next statement to be executed is an operator throw
.
There are two situations that can cause the debugger to end up in the same place when it is not:
- Compilation with optimizations enabled (very common, by default - in the Release configuration ).
- Using IL rewrite tools that incorrectly update debug information (not very often).
Recompiling or Running the Code Using Configuration Debugging will most likely show you that the statement has throw
not actually been reached.
source to share