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 ... enter image description here

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 .

enter image description here

+3


source to share


4 answers


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.

0


source


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.

0


source


The graph doesn't work like that. Use verbs.Length

instead

-1


source


I'm not sure I can tell you why you are seeing this result, but I can suggest a fix: use verbs.Length instead of verbs.Count (). In this case, Count () is a LINQ method and Length is an array property that will tell you the number of elements in the array.

-4


source







All Articles