Home >Backend Development >C++ >How Can I Determine if a Type Implements a Specific Generic Interface in C#?

How Can I Determine if a Type Implements a Specific Generic Interface in C#?

Barbara Streisand
Barbara StreisandOriginal
2025-01-07 07:19:41872browse

How Can I Determine if a Type Implements a Specific Generic Interface in C#?

Determining if a Type Implements a Specific Generic Interface Type

Suppose you have the following type definitions:

public interface IFoo<T> : IBar<T> {}
public class Foo<T> : IFoo<T> {}

Given only the mangled type, how can you determine if the type Foo implements the generic interface IBar?

Solution with LINQ Query

As suggested by TcKs, you can utilize the following LINQ query:

bool isBar = foo.GetType().GetInterfaces().Any(x =>
  x.IsGenericType &amp;&amp;
  x.GetGenericTypeDefinition() == typeof(IBar<>));

This query checks if any of the implemented interfaces of foo is a generic type that matches the IBar definition. The Any() method returns true if at least one interface meets that criteria.

The above is the detailed content of How Can I Determine if a Type Implements a Specific Generic Interface in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn