runtime: Exclude generic types with parameters that do not satisfy constraints

Description

When analyzing my application using sizoscope, I discovered that the final build contains generic classes whose type parameters violate the declared constraints. This can lead to an increase in the build size and create confusion during code analysis.

Example class:

internal sealed class GenericMathConverter<TFrom, TTo> : TypeConverterBase<TFrom, TTo>
    where TFrom : INumberBase<TFrom>
    where TTo : INumberBase<TTo>
{
    public override bool TryConvert(TFrom from, [MaybeNullWhen(false)] out TTo value)
    {
        try
        {
            value = TTo.CreateTruncating(from);
            return true;
        }
        catch
        {
            value = default;
            return false;
        }
    }
}

An instance of this class is created via reflection as follows:

if (typeof(ISpanFormattable).IsAssignableFrom(typeof(TFrom)) && typeof(IComparable<TFrom>).IsAssignableFrom(typeof(TFrom)) &&
    typeof(ISpanFormattable).IsAssignableFrom(typeof(TTo)) && typeof(IComparable<TTo>).IsAssignableFrom(typeof(TTo)))
{
    return Activator.CreateInstance(typeof(GenericMathConverter<,>).MakeGenericType(typeof(TFrom), typeof(TTo)));
}

Note that the reflection creation condition checks for ISpanFormattable and IComparable<T>, whereas the class constraints require the implementation of INumberBase<T> but I can’t check it in runtime and I use these interfaces to reduce false positive creation.

This is a screenshot from the sizoscope, it contains a lot of types which do not implement the INumberBase interface moreover they do not implement ISpanFormattable and IComparable<T> (I included only part of them). They cannot be physically used even if one attempts to create them via reflection as the constraints will prevent it. Therefore, the question arises, why include these types in the release build? Image

Reproduction Steps

Attempt to create a generic type via reflection using types that violate the constraints, and then verify the result with sizoscope.

Expected behavior

The type should not be included in the release build.

Actual behavior

The type is included in the release build.

Regression?

No response

Known Workarounds

No response

Configuration

No response

Other information

No response

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Comments: 16 (7 by maintainers)

Most upvoted comments

We probably eliminate the branch during codegen if it’s possible (it’s only possible if both TFrom and TTo are structs). But we don’t eliminate it during whole program analysis (that analyzes things like Activator calls). If codegen can eliminate it, we’ll eliminate it during whole program analysis too if/when #83021 is done, but it’s not done yet.