Disregarding any other problem conceptual or otherwise
Since all you are doing is checking if a control is of a certain type, the easiest way is to use the Enumerable.OfType<TResult>
method.
Filters the elements of an IEnumerable
based on a specified type.
Then all that is needed is to call Enumerable.Any
Determines whether any element of a sequence exists or satisfies a
condition.
Example
// lets check our cast and show off the new #9 pattern matching negation
if (sender is not Panel panel)
throw new InvalidOperationException("Whoops");
var flag = panel
.Controls
.OfType<Something>()
.Any();
...
The longer story is, ControlCollection.Controls
only supports
- IList
- ICollection
- IEnumerable (Non generic)
Not IEnumerable<T>
so you are limited by what you can call.
However, IEnumerable<TResult> OfType<TResult>(this IEnumerable source)
can take the non generic IEnumerable
parameter, and returns an IEnumerable<T>
giving you access to all of the extension methods you know and love.