I have the following code, where T is a generic defined as such:
public abstract class RepositoryBase<T> where T : class, IDataModel
This code works just fine:
PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
if (propertyInfo.DeclaringType.FullName == typeof(T).FullName) <--- Works just fine
vs this code which evaluates to false
PropertyInfo propertyInfo = typeof(T).GetProperty(propertyName);
if (propertyInfo.DeclaringType is T) <-- does not work
What am I doing wrong here?
is uses type comparison between the two objects. So DeclaringType
is of type Type
and typeof(T)
is of type T
, which are not equal.
var aType = typeof(propertyInfo.DeclaringType);
var bType = typeof(T);
bool areEqual = aType is bType; // Always false, unless T is Type
What you are looking for is
TypeIsAssignableFrom
if (propertyInfo.DeclaringType.IsAssignableFrom(typeof(T)))
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