Compare types if one is nullable

Viewed 1448

I need to check if two types are the same:

private bool AreOfTheSameType(object obj1, object obj2) {
  return obj1.GetType()==obj2.GetType();
}

This works fine with this values:

var test1=AreOfTheSameType(new DateTime(), new DateTime()) // true;
var test2=AreOfTheSameType(new int(), new DateTime()) // false;

What I now want is that the following returns true, too:

var test3=AreOfTheSameType(new int?(), new int()) 

So if the types have the same base, but one is nullable, the other isn't, I also want to return it as true. Or to say it in another way I want to have a function that returns whether I can store obj1 into obj2 directly using reflection without having to cast the value.

UPDATE

I reduced my code to make it more readable. Looks like this time that was contra-productive. The real-world-code follows:

var entity = Activator.CreateInstance(typeof(T));
Type entityType = typeof(T);
PropertyInfo[] entityProperties = entityType.GetProperties();
foreach (KeyValuePair<string, object> fieldValue in item.FieldValues)
{
   if (fieldValue.Value == null) continue;
   var property = entityProperties.FirstOrDefault(prop => prop.Name == fieldValue.Key);
   if (property != null && property.CanWrite)
   {
      Type valueType = fieldValue.Value.GetType();
      if (fieldValue.Value.GetType() == property.PropertyType) {
        // Assign
      }
   }
}

The problem on the "//Assign" - line is, I have the following two types:

fieldValue.Value.GetType().ToString()="System.DateTime"
property.PropertyType.ToString()="System.Nullable`1[System.DateTime]"

which are obiously not the same but could be assigned

3 Answers
Related