question

NileshVishwakarma avatar image
0 Votes"
NileshVishwakarma asked ·

.Net 5.0 | IsAssignableTo not working with generic interface

Hello Microsoft Team,

I have question regarding IsAssignableTo Method
Url : https://docs.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.

dotnet-csharpdotnet-runtimedotnet-runtime-core
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered ·

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?

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.