Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my C# IS statement not working?

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?

like image 361
Scottie Avatar asked Sep 24 '13 17:09

Scottie


2 Answers

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
like image 90
Will Custode Avatar answered Oct 17 '22 17:10

Will Custode


What you are looking for is

TypeIsAssignableFrom

if (propertyInfo.DeclaringType.IsAssignableFrom(typeof(T)))
like image 25
Boas Enkler Avatar answered Oct 17 '22 15:10

Boas Enkler