I am trying to return the object type of the class that implements the interface defined in the code below.
The linq statement only returns the interface itself, and so the console output is just:
AssignableExperiment.IRule
Why isn’t the concrete class being returned?
using System;
using System.Linq;
namespace AssignableExperiment
{
public interface IRule
{
void Validate(string s);
}
public class ConcreteRule : IRule
{
public void Validate(string s)
{
// some logic
}
}
class Program
{
static void Main(string[] args)
{
var ruleType = typeof(IRule);
var ruleTypes = from t in ruleType.Assembly.GetTypes()
where t.IsAssignableFrom(ruleType)
select t;
foreach (var type in ruleTypes)
{
Console.WriteLine(type);
}
Console.ReadLine();
}
}
}
You should turn it around the
IsAssignableFromMSDN. BecauseIsAssignableFromworks another way around as expected:BaseType.IsAssignableFrom(DerviedType)returns true.If you don’t want to get back
IRule: