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 IsAssignableFrom
MSDN. Because IsAssignableFrom
works another way around as expected: BaseType.IsAssignableFrom(DerviedType)
returns true.
var ruleTypes = from t in ruleType.Assembly.GetTypes()
where ruleType.IsAssignableFrom(t)
select t;
If you don't want to get back IRule
:
var ruleTypes = from t in ruleType.Assembly.GetTypes()
where ruleType.IsAssignableFrom(t) && t != ruleType
select t;
I hate the IsAssignableFrom, it is so nefariously written.
I always roll the extension:
public static bool IsTypeOf<T>(this Type type)
{
return typeof (T).IsAssignableFrom(type);
}
Using this prevents insidious errant execution.
Then you could write:
var ruleTypes = ruleType.Assembly.GetTypes().Where(t=> t.IsTypeOf<IRule>());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With