jeudi 1 juin 2017

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.





Aucun commentaire:

Enregistrer un commentaire