Search code examples
c#exceptionicollection

Print the number of elements in an ICollection in an exception message


I have a collection of items and I want to throw an exception to the user, how many items there are in the collection - if it contains more or less than 1.

This might seem quite simple, but I don't know how to print the number of elements it contains.

my collection variable is called myCollection and it contains 3 elements.

I've tried something like this:

if(myCollection?.count != 1){
    throw new ArgumentOutOfRangeException("myCollection contains {0} elements", myCollection?.count}
}

But it tells me, the following:

"Cannot convert from 'int' to 'System.Exception"

Can anyone help, please.


Solution

  • In order to format the exception message as in OP, you could use either of the following approaches

    throw new ArgumentOutOfRangeException(string.Format("myCollection contains {0} elements", myCollection?.count));
    

    or

    throw new ArgumentOutOfRangeException($"myCollection contains {myCollection?.count} elements);