'How to get underlying type of generic interface?

public class TestBase
{
    // implementation
}
public class Test : ICollection<TestBase>
{
    // implementation
}

Somewhere else I have a property of the Test type:

public Test Test {get;set;}

How can I get the underlying type of the ICollection that the Test inherits from?



Solution 1:[1]

What you are probably looking for is GetGenericArguments().

var type = typeof(Test);
var collInterface = type.GetInterfaces()[0];
var generic = collInterface.GetGenericArguments()[0];

Solution 2:[2]

Let x be an instance of a class that implements interfaces. You can get its iterface types as follows:

var type = x.GetType();
var interfaces = type.GetInterfaces();

Edit: I had your question wrong: Follow up with "GetGenericArguments()" as suggested.

Solution 3:[3]

the GetInterfaces method returns all implemented interfaces in current type and its GetGenericArguments method returns list of generic arguments witch you can get its base type by BaseType property. this example returns class hierarchy of the generic argument of base interface implemented in current class:

var myType = this.GetType().GetInterfaces().First().GetGenericArguments().First(); while (myType != null)
{
Console.WriteLine(myType.Name);
myType = myType.BaseType;
}

Solution 4:[4]

Just a different approach of getting the used type in a base interface:

private readonly IObjectProvider<Interface> _repositoryInterfaces = 
    Interfaces().That().ImplementInterface(typeof(IRepository<>)).As("Repository Interfaces");

[Fact]
public void RepositoryInterfaces_ShouldBeInTheCorrectNamespace()
{
    // Arrange
    var repos = Interfaces().That().Are(_repositoryInterfaces).GetObjects(Architecture);

    // Act
    // Assert
    foreach (var repo in repos)
    {
        var entityType = repo.GetImplementsInterfaceDependencies().Single().TargetGenericArguments.Single().Type;

        repo.ResidesInNamespace($"Domain.AggregateModels.{entityType.Name}Aggregate").Should().BeTrue();
    }
}

my interfaces look like this:

public interface IExampleRepository : IRepository<ExampleEntity>
{ //more methods here }

Solution 5:[5]

 Type t = typeof(Test);
 MethodInfo mi = t.GetMethod("MyMethod");
 Type returnvalue = mi.ReturnType;
 Type answer = Nullable.GetUnderlyingType(returnvalue);

I hope it helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Toxantron
Solution 2
Solution 3 mehrdad safa
Solution 4 Ilias.P
Solution 5 TJ Riceball