Should be easy…
class Base{}
class Foo:Base{}
public bool Bar(Type t){
// return ???
// NB: shouldn't know anything about Foo, just Base
}
Assert.True(Bar(typeof(IEnumerable<Foo>));
Assert.False(Bar(typeof(IEnumerable<Base>));
Assert.False(Bar(typeof(string));
Assert.False(Bar(typeof(Foo));
Just to answer question why 2nd one should be false (actually – it does not matter, cause Bar argument will never be IEnumerable<Base>).
I’m trying to write FluentNhibernate auto mapping convention which maps my class enumerations to integers. I successfully did that already, but things went down when I wanted to map IEnumerable<EnumerationChild> (in my case – User.Roles).
public class EnumerationConvention:IUserTypeConvention{
private static readonly Type OpenType=typeof(EnumerationType<>);
public void Apply(IPropertyInstance instance){
//this is borked atm, must implement ienumerable case
var closedType=OpenType.MakeGenericType(instance.Property.PropertyType);
instance.CustomType(closedType);
}
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria){
criteria.Expect(
x=>typeof(Enumeration).IsAssignableFrom(x.Property.PropertyType) ||
typeof(IEnumerable<Enumeration>)
.IsAssignableFrom(x.Property.PropertyType));
}
}
You can use
Type.IsAssignableFrom(Type). However, your question isn’t really clear – you’re specifying one type, but you need two… which type isBarmeant to be checkingtagainst?Note that the answer will change between .NET 3.5 and .NET 4, due to generic covariance – in .NET 3.5, for example, a
List<Foo>is not assignable toIEnumerable<Base>, but in .NET 4 it is.EDIT: Here’s a program which prints True, True, False, False. I’m not sure why you expected the second one to be false: