ExtensionMethod.NET Home of 877 C#, Visual Basic, F# and Javascript extension methods


Determines if there is an element of a given type inside a collection.


namespace System.Collections;

public static class EnumerableExtensions
    /// <summary>
    /// Determines if there is an element of type <typeparam name="T"> </typeparam> inside a <see cref="IEnumerable" />.
    /// </summary>
    /// <typeparam name="T">Actual type to look for</typeparam>
    /// <param name="source">Source collection.</param>
    /// <returns>True if there is an element whose type is <typeparam name="T"/></returns>
    public static bool AnyOfType<T>(this IEnumerable source)
        foreach (var obj in source)
            if (obj is T)
                return true;

        return false;


object[] myList = new object[]
    new StringBuilder()
Console.WriteLine(myList.AnyOfType<string>()); // Returns true
Console.WriteLine(myList.AnyOfType<bool>()); // Returns false

Author: Maxime Poulain

Submitted on: 22 jun. 2022

Language: csharp

Type: System.Collections.IEnumerable

Views: 4382