简体   繁体   中英

Compare types if one is nullable

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

which are obiously not the same but could be assigned

It looks like you're after the Type.IsAssignableFrom method:

var dt = typeof(DateTime);            
var nd = typeof(DateTime?);

Console.WriteLine(dt.IsAssignableFrom(nd)); // false
Console.WriteLine(nd.IsAssignableFrom(dt)); //true

Live example: http://rextester.com/KDOW15238

Calling GetType on nullable types returns the original type:

int? i = 5;  
Type t = i.GetType();  
Console.WriteLine(t.FullName); //"System.Int32"  

So AreOfTheSameType((int?)5, 5) should return true .

But as soon as you box a Nullable<T> , you either get null (if Nullable<T>.HasValue was false ), or you get the boxed underlying value, losing the "nullable" part. So the problem you're facing here is that new int? will be boxed into a null object when passed to the method.

The problem with nullable types is that empty values box to null , and once they're null , you cannot find out what they were. The only way to solve this, then, is with generics:

private bool AreOfTheSameType<T1,T2>(T1 obj1, T2 obj2) {
  // get the types as best we can determine
  var t1 = obj1?.GetType() ?? typeof(T1);
  var t2 = obj2?.GetType() ?? typeof(T2);

  // Nullable<T> => T
  t1 = Nullable.GetUnderlyingType(t1) ?? t1;
  t2 = Nullable.GetUnderlyingType(t2) ?? t2;

  // compare
  return t1 == t2;
}

This will use the object if available (to allow for subclasses etc), but will fall back to typeof if the object is null - which means it should work for int? etc... as long as the type of the expression being passed in wasn't object to begin with; if it was object and the value is null , then... you're out of luck - you can't ever find out the original type. By which I mean:

This should be fine:

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

But this will fail:

object x = new int?(), y = new int();
var test4=AreOfTheSameType(x, y);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM