Skip to content

Add Type.GetInterfacesWithSameMetadataDefinitionAs - #137016

Merged
jkotas merged 17 commits into
dotnet:mainfrom
Manish-1kumar:users/Manish-1kumar/type-getinterfaces-same-definition
Nov 24, 2026
Merged

jkotas merged 17 commits into
dotnet:mainfrom
Manish-1kumar:users/Manish-1kumar/type-getinterfaces-same-definition

Conversation

@Manish-1kumar

@Manish-1kumar Manish-1kumar commented Nov 5, 2026 •

Copy link
Copy Markdown
Contributor

Implements the API approved in #136546:

public virtual Type[] GetInterfacesWithSameMetadataDefinitionAs(Type interfaceType);

The implementation follows GetMemberWithSameMetadataDefinitionAs: it filters GetInterfaces() with HasSameMetadataDefinitionAs, and suppresses IL2085 with the same reasoning as the existing ImplementInterface helper. If interfaceType exists, trimming kept the matching interface implementations, so the result is complete relative to what's reachable.

Behavior

The approval doesn't spell these out. Following review, the behavior matches GetMemberWithSameMetadataDefinitionAs:

  • interfaceType can be any type, as with GetMemberWithSameMetadataDefinitionAs. A generic interface type definition (typeof(IList<>)) or any of its instantiations matches every instantiation the type implements, so IList<int> also matches an implemented IList<string>. A type that isn't an interface matches nothing.
  • Interfaces inherited from base classes and through other interfaces are included, as with GetInterfaces(). An interface type doesn't match itself.
  • null throws ArgumentNullException; nothing else throws.
  • No match returns Type.EmptyTypes. The order of the results isn't defined.

Testing

New tests in TypeInfoTests cover generic definitions and constructed forms, base-class and interface inheritance, non-generic interfaces, no match, a generic type definition as the current type, framework types (int, List<string>, arrays), and argument validation. The same cases were also run against a copy of the implementation on .NET 10. CoreLib (with the trimming analyzers), the System.Runtime ref (including API compat) and System.Reflection.Tests build cleanly.

Fixes #136546

🤖 Generated with Claude Code

Add the API approved in dotnet#136546. It returns the interfaces implemented or
inherited by a type that have the same metadata definition as the specified
interface, which gives a trim-safe way to find all instantiations of a
generic interface.

Fixes dotnet#136546

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@dotnet-policy-service dotnet-policy-service Bot added the community-contribution Indicates that the PR has been added by a community member label Nov 5, 2026
@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines:
Successfully started running 3 pipeline(s).
12 pipeline(s) were filtered out due to trigger conditions.
There may be pipelines that require an authorized user to comment /azp run to run.

@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Tagging subscribers to this area: @steveisok, @dotnet/area-system-reflection
See info in area-owners.md if you want to be subscribed.

@Manish-1kumar
Manish-1kumar marked this pull request as draft November 5, 2026 12:08
@jkotas

jkotas commented Nov 5, 2026

Copy link
Copy Markdown
Member
  • We may want to add more efficient implementations for specific System.Type implementations (include number that showing that the specific implementations are significantly faster).
  • Are there places in this repo where this API can be used?

Move matching interfaces to the front of the array returned by
GetInterfaces and trim it with Array.Resize instead of iterating twice.
Throw ArgumentException for constructed generic interfaces; callers pass
the generic type definition instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Manish-1kumar

Copy link
Copy Markdown
Contributor Author

Thanks for the review!

  • Specialized implementations: I've kept the base implementation for now. The obvious candidate is RuntimeType, which could filter the cached interface list directly and avoid copying the full GetInterfaces() array. I'll measure it and only propose it if it's significantly faster, with the numbers.

  • Uses in this repo: these places filter GetInterfaces() by a fixed generic interface definition and could use the new API:

    • System.Linq.Queryable: EnumerableRewriter (IEnumerable<>)
    • System.Private.DataContractSerialization: CollectionDataContract, JsonFormatWriterGenerator, XmlFormatWriterGenerator (IEnumerator<>)

    I'm happy to switch them over in a follow-up PR once this one is in, or here if you'd prefer.

Also, per @agocke's feedback on the issue, constructed generic interfaces now throw ArgumentException (d9fddff). Callers pass the generic type definition instead.

@jkotas

jkotas commented Nov 5, 2026

Copy link
Copy Markdown
Member

here if you'd prefer.

Yes

Replace loops over GetInterfaces() that filter by a generic interface
definition in System.Linq.Queryable and DataContract serialization.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Manish-1kumar

Copy link
Copy Markdown
Contributor Author

Done in eedc3d6:

  • EnumerableRewriter.GetPublicType (IEnumerable<>)
  • CollectionDataContract, JsonFormatWriterGenerator and XmlFormatWriterGenerator (IEnumerator<>, still checking the item type)

The order of the results matches GetInterfaces(), so GetPublicType returns the same interface as before. Both libraries build cleanly, including the trimming analyzers.

@jkotas

jkotas commented Nov 5, 2026

Copy link
Copy Markdown
Member

Can

public static Type? GetCompatibleGenericInterface(this Type type, Type? interfaceType)
use this API?

Update GetCompatibleGenericInterface in ReflectionExtensions.cs to use
Type.GetInterfacesWithSameMetadataDefinitionAs under NET12_0_OR_GREATER.
Addresses review feedback from @jkotas on dotnet#137016.
@MichalStrehovsky

Copy link
Copy Markdown
Member

Can these use the new API?

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:RequiresUnreferencedCode",
Justification = "GetInterfaces is only called if 'definition' is interface type. " +
"In that case though the interface must be present (otherwise the Type of it could not exist) " +
"which also means that the trimmer kept the interface and thus kept it on all types " +
"which implement it. It doesn't matter if the GetInterfaces call below returns fewer types" +
"as long as it returns the 'definition' as well.")]
internal static Type? FindGenericType(Type definition, Type type)
{
bool? definitionIsInterface = null;
while (type != null && type != typeof(object))
{
if (type.IsGenericType && type.GetGenericTypeDefinition() == definition)
return type;
if (!definitionIsInterface.HasValue)
definitionIsInterface = definition.IsInterface;
if (definitionIsInterface.GetValueOrDefault())
{
foreach (Type itype in type.GetInterfaces())
{
Type? found = FindGenericType(definition, itype);
if (found != null)
return found;
}
}
type = type.BaseType!;
}
return null;

private static Type? FindOpenGenericInterface(
Type expected,
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.Interfaces)]
Type actual)
{
if (actual.IsGenericType &&
actual.GetGenericTypeDefinition() == expected)
{
return actual;
}
Type[] interfaces = actual.GetInterfaces();
foreach (Type interfaceType in interfaces)
{
if (interfaceType.IsGenericType &&
interfaceType.GetGenericTypeDefinition() == expected)
{
return interfaceType;
}
}
return null;

Debug.Assert(type != null, "Type should only be null for the well-known static fetchers already checked");
TypeInfo typeInfo = type.GetTypeInfo();
if (propertyName == EnumeratePropertyName)
{
// If there are multiple implementations of IEnumerable<T>, this arbitrarily uses the first one
foreach (Type iFaceType in typeInfo.GetInterfaces())
{
TypeInfo iFaceTypeInfo = iFaceType.GetTypeInfo();
if (!iFaceTypeInfo.IsGenericType ||
iFaceTypeInfo.GetGenericTypeDefinition() != typeof(IEnumerable<>))
{
continue;
}
return CreateEnumeratePropertyFetch(type, iFaceTypeInfo);
}
// no implementation of IEnumerable<T> found, return a null fetcher
eventSource.Message($"*Enumerate applied to non-enumerable type {type}");
return new PropertyFetch(type);

[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2070:UnrecognizedReflectionPattern",
Justification = "The derived type was supplied via [JsonDerivedType] by the user, so its interface " +
"metadata is rooted at the attribute usage site and survives trimming. Callers are " +
"additionally annotated [RequiresUnreferencedCode] to flow this requirement outward.")]
public static IEnumerable<Type> GetMatchingGenericBaseTypes(this Type type, Type baseTypeDefinition)
{
Debug.Assert(baseTypeDefinition.IsGenericTypeDefinition);
if (baseTypeDefinition.IsInterface)
{
foreach (Type iface in type.GetInterfaces())
{
if (iface.IsGenericType && iface.GetGenericTypeDefinition() == baseTypeDefinition)
{
yield return iface;
}
}
// Note: do NOT yield break here. Type.GetInterfaces() does not include `type`
// itself, so when `type` IS the interface we're looking for, the fall-through
// to the BaseType walk below picks it up via the self-check on the first
// iteration (Type.BaseType returns null for interfaces, so the loop
// terminates immediately).
}
for (Type? current = type; current is not null; current = current.BaseType)
{
if (current.IsGenericType && current.GetGenericTypeDefinition() == baseTypeDefinition)
{
yield return current;
yield break;
}
}

Replace GetInterfaces() loops filtering by a generic interface definition in
System.Linq.Queryable (TypeHelper), Microsoft.Extensions.Configuration.Binder,
System.Diagnostics.DiagnosticSource and System.Text.Json. Multi-targeted
libraries keep the existing loop for frameworks without the new API.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Manish-1kumar

Copy link
Copy Markdown
Contributor Author

Yes, all four can. Updated in 83ac9e2:

  • System.Linq.Queryable TypeHelper.FindGenericType: the interface case is now a single call, and the IL2070 suppression is gone since it no longer calls GetInterfaces(). The class path (e.g. Expression<>) still walks the base types. One subtle difference: when a type implements several instantiations, the old recursive walk could return a match found through a nested interface before an earlier direct match. Now it's the first match in GetInterfaces() order.
  • ConfigurationBinder.FindOpenGenericInterface and DsesFilterAndTransform (IEnumerable<>): direct replacements.
  • System.Text.Json GetMatchingGenericBaseTypes: the interface branch now uses the API. The order still matches GetInterfaces(), which the source generator mirrors.

Configuration.Binder, DiagnosticSource and System.Text.Json also target older frameworks, so they keep the existing loop under #if !NET12_0_OR_GREATER, like the earlier GetCompatibleGenericInterface change. All four build cleanly for every target framework.

Replace the #if NET12_0_OR_GREATER fallbacks in System.Text.Json,
Microsoft.Extensions.Configuration.Binder and System.Diagnostics.DiagnosticSource
with a TypePolyfills extension for older target frameworks, and remove the
IL2070 suppressions that were unused on net12.0 (IL2121).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…itionAs polyfill

Include the polyfill only for target frameworks older than net12.0, so it stops
being compiled for .NETCoreApp once NetCoreAppMinimum moves to .NET 12.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…thSameMetadataDefinitionAs

Most calls match a single interface, which ListBuilder handles without allocating
backing storage, and RuntimeTypes can be compared by reference. Don't presize the
builder for every candidate: that over-allocated when several interfaces matched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ameMetadataDefinitionAs

The candidates are compared by reference, so an interfaceType that isn't a
RuntimeType never matches. Validate interfaceType directly and add a test for a
non-runtime interface type.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@jkotas jkotas left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

…DefinitionAs

For types with a non-generic-definition MethodTable, walk the interface map and
compare MethodTables directly, creating Type objects only for the matches. Other
cases fall back to the base implementation.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Compare the generic definition of each implemented interface (or the
interface itself when it isn't generic) with interfaceType, instead of
branching on whether interfaceType is a generic type definition.
Match GetMemberWithSameMetadataDefinitionAs: only null throws. A
constructed generic interface matches every instantiation of its
definition, and a type that isn't an interface matches nothing.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Move the GetInterfacesWithSameMetadataDefinitionAs polyfill into
TypePolyfills.cs, remove a DynamicallyAccessedMembers annotation and a
cached flag that are no longer needed, and use the same indexing pattern
in System.Text.Json as at the other call sites.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

The tests explicitly root expected interface instantiations, leaving discovery without separate rooting and trimming-warning behavior unverified under ILLink and NativeAOT.

1 open issue
What changed in this PR

Adds Type.GetInterfacesWithSameMetadataDefinitionAs to support trim-safe interface discovery by metadata definition, addressing the scenario described in #136546.

Changes:

  • Adds the public API, documentation, and specialized CoreCLR and NativeAOT implementations.
  • Migrates library interface searches to the new API and provides a polyfill for older targets.
  • Adds reflection tests for matching, inheritance, generic types, and argument validation.
File Description
src/​libraries/​System.Text.Json/​src/​System/​ReflectionExtensions.cs Uses the API for generic interface enumeration.
src/​libraries/​System.Text.Json/​src/​System.Text.Json.csproj Includes the polyfill on older targets.
src/​libraries/​System.Text.Json/​Common/​ReflectionExtensions.cs Simplifies compatible interface lookup.
src/​libraries/​System.Runtime/​tests/​System.Reflection.Tests/​TypeInfoTests.cs Adds API behavior and validation tests.
src/​libraries/​System.Runtime/​ref/​System.Runtime.cs Declares the public API.
src/​libraries/​System.Private.DataContractSerialization/​src/​System/​Runtime/​Serialization/​XmlFormatWriterGenerator.cs Filters XML collection enumerator interfaces.
src/​libraries/​System.Private.DataContractSerialization/​src/​System/​Runtime/​Serialization/​Json/​JsonFormatWriterGenerator.cs Filters JSON collection enumerator interfaces.
src/​libraries/​System.Private.DataContractSerialization/​src/​System/​Runtime/​Serialization/​CollectionDataContract.cs Updates collection enumerator discovery.
src/​libraries/​System.Private.CoreLib/​src/​System/​Type.cs Implements and documents the default API.
src/​libraries/​System.Linq.Queryable/​src/​System/​Linq/​TypeHelper.cs Simplifies generic interface discovery.
src/​libraries/​System.Linq.Queryable/​src/​System/​Linq/​EnumerableRewriter.cs Uses filtered enumerable interface lookup.
src/​libraries/​System.Diagnostics.DiagnosticSource/​src/​System/​Diagnostics/​DsesFilterAndTransform.cs Updates enumerable property-fetch discovery.
src/​libraries/​System.Diagnostics.DiagnosticSource/​src/​System.Diagnostics.DiagnosticSource.csproj Includes the polyfill on older targets.
src/​libraries/​Microsoft.Extensions.Configuration.Binder/​src/​Microsoft.Extensions.Configuration.Binder.csproj Includes the polyfill on older targets.
src/​libraries/​Microsoft.Extensions.Configuration.Binder/​src/​ConfigurationBinder.cs Simplifies open generic interface lookup.
src/​libraries/​Common/​src/​Polyfills/​TypePolyfills.cs Adds the downlevel API equivalent.
src/​coreclr/​System.Private.CoreLib/​src/​System/​RuntimeType.CoreCLR.cs Filters cached runtime interfaces directly.
src/​coreclr/​nativeaot/​System.Private.CoreLib/​src/​System/​RuntimeType.NativeAot.cs Adds direct interface-map matching with fallback.

Review effort: Balanced

@jkotas
jkotas merged commit ae0d237 into dotnet:main Nov 24, 2026
104 of 106 checks passed
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area-System.Reflection community-contribution Indicates that the PR has been added by a community member

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[API Proposal]: Trim-safe Type.GetInterfaces() filtering output based on type definition

5 participants