.Net 5.0 | IsAssignableTo not working with generic interface

Nilesh Vishwakarma 1 Reputation point
2021-03-20T20:39:40.913+00:00

Hello Microsoft Team,

I have question regarding IsAssignableTo Method
Url : https://learn.microsoft.com/en-us/dotnet/api/system.type.isassignableto?view=net-5.0

When I try to check my class has assignable interface(generic) or not.
So I am using IsAssignableTo method to check, it is give me true or false.
It is working fine in asp.net core 3.1 but when I use it with 5.0, it is not working.
It always returns false when I use generic Interface.

Here is my sample code,
var status = typeof(MyClass).IsAssignableTo(IMyInterface<,>)

public class MyClassModel{}

public interface IMyInterface<MyClassModel,int>{}

public class MyClass : IMyInterface<MyClassModel,int>{}

  • IsAssignableTo is always return false when I check MyClass is implemented Generic Interface.

Could you please provide some solution to resolve this issue?

Thanks.

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
7,022 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: The period of time during which a program is being executed in a computer.
960 questions
No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Viorel 83,016 Reputation points
    2021-03-21T07:10:38.41+00:00

    Maybe the result is correct, because MyClass cannot be assigned to all of IMyInterface<,> (such as IMyInterface<string, long>, for example), but it can be assigned to particular IMyInterface<MyClassModel, int>. This returns true: typeof( MyClass ).IsAssignableTo( typeof( IMyInterface<MyClassModel, int> ) ).

    To check that MyClass implements the generic IMyInterface, try something like this:

    bool result = typeof( MyClass )
       .GetInterfaces( )
       .Any( i => i.IsGenericType && i.GetGenericTypeDefinition( ) == typeof( IMyInterface<,> ) );
    

    Are you sure that IsAssignableTo was available in .NET Core 3.1?

    No comments