Dynamically set generic type argument
- by fearofawhackplanet
Following on from my question here, I'm trying to create a generic value equality comparer. I've never played with reflection before so not sure if I'm on the right track, but anyway I've got this idea so far:
bool ContainSameValues<T>(T t1, T t2)
{
if (t1 is ValueType || t1 is string)
{
return t1.Equals(t2);
}
else
{
IEnumerable<PropertyInfo> properties = t1.GetType().GetProperties().Where(p => p.CanRead);
foreach (var property in properties)
{
var p1 = property.GetValue(t1, null);
var p2 = property.GetValue(t2, null);
if( !ContainSameValues<p1.GetType()>(p1, p2) )
return false;
}
}
return true;
}
This doesn't compile because I can't work out how to set the type of T in the recursive call. Is it possible to do this dynamically at all?
There are a couple of related questions on here which I have read but I couldn't follow them enough to work out how they might apply in my situation.