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.
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