if o.GetType() == sometype
is it guaranteed that o
can be casted to sometype
?
that is if:
void f<T>(T o1, object o2) {
if (o1.GetType() != o2.GetType()) return;
T t = o2 as T;
// can I assert that t is not null ??
}
if o.GetType() == sometype
is it guaranteed that o
can be casted to sometype
?
that is if:
void f<T>(T o1, object o2) {
if (o1.GetType() != o2.GetType()) return;
T t = o2 as T;
// can I assert that t is not null ??
}
Yes, you can, but I'd suggest going one step further and do this:
void f<T, U>(T t, U u) where T : class
{
if (!t.GetType().IsAssignableFrom(u.GetType())) return;
T ut = u as T;
// can I assert that t is not null ?? Yes, you can
}
IsAssignableFrom
should nail it for any type.
Why not just use the is
operator, 1Albeit "maybe" a little slower
if (o2 is SomeType result) o1 = result;
or as a method
private void SomeThingWeird<T>(ref T o1, object o2)
{
if (o2 is T result)
o1 = result;
}
References
1 Drilling into .NET Runtime microbenchmarks: ‘typeof’ optimizations.
Why not doing :
void f<T>(T o1, T o2) {
if (o1.GetType() != o2.GetType()) return;
// can I assert that t is not null ??
}
For what I understand you want, by checking if (o1.GetType() != o2.GetType()) return;
to make sure that o2
is of type T
and not a derived type. So o2
has to be of type T
and you don't have any problem casting.