0

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 ??
}
Camilo Terevinto
  • 31,141
  • 6
  • 88
  • 120
kofifus
  • 17,260
  • 17
  • 99
  • 173
  • 3
    This looks like an XY problem, or at least there's a code smell here... – DavidG Mar 17 '19 at 22:28
  • 2
    Yes, it's guaranteed, but that code doesn't make a lot of sense as-is – Camilo Terevinto Mar 17 '19 at 22:28
  • To be specific, your code violates this: https://en.wikipedia.org/wiki/Liskov_substitution_principle –  Mar 17 '19 at 22:30
  • Sounds to me like you actually want to use interfaces. Generics are not that. – GolezTrol Mar 17 '19 at 22:30
  • it's part of a bigger thing, if you look at my extension method here https://stackoverflow.com/a/54934113/460084 I was wondering if the `&& obj is T o && thisEquals(o)` can be safely shortcutted to `&& thisEquals(o as T)` ? – kofifus Mar 17 '19 at 22:34
  • 2
    Obviously not going to work for value types. Regular cast would be fine – Alexei Levenkov Mar 17 '19 at 22:56
  • 1
    There is no guarantee that `T` and `o1.GetType()` will be the same type (`T` could be `object` for example, while `GetType()` would return the **real** type). I am not saying that is a problem, just pointing it out in case it impacts your solution. – mjwills Mar 17 '19 at 23:45

3 Answers3

1

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.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
1

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.

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
-1

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.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
La pieuvre
  • 438
  • 2
  • 9