1

I have a set up approximately like this:

public class A { ... }
public class A<T> : A { ... }
public class B<T> : A<T> { ... }
public class C : B<SomeType> { ... }

I am iterating over a list of type A, and I want to check if something is of type B, and if it is, convert it to... B... I can see how it already poses a problem of how am I gonna get the type... but if I cannot do that, what are my other alternatives?

EDIT: To clarify, B contains a method I'd like to use that A does not contain as it simply has no need for it... I want to check which of the objects on that list are of type B so that I can run this method on them

EDIT 2: I forgot to mention the A in the middle earlier... sorry for the confusion

1Mangomaster1
  • 346
  • 1
  • 6
  • 16

1 Answers1

1

I want to check which of the objects on that list are of type B

Then introduce a type B into your type hierarchy. Currently you don't have a type B, you've got B<SomeType> which is a different type. so

public class A { ... }

public abstract class B : A { ... }

public class B<T> : B { ... }

public class C : B<SomeType> { ... }

Or declare the method you want on an interface

public class A { ... }
public class A<T> : A { ... }
public interface IB
public class B<T> : A<T>, IB { ... }
public class C : B<SomeType> { ... }

Then for any A you can check if it is IB. This is probably the most natural solution since .NET doesn't have multiple inheritance.

David Browne - Microsoft
  • 80,331
  • 6
  • 39
  • 67
  • That's... a problem... you see the real tree in my example looks like: A, A, B, C... I cannot introduce a B in the middle – 1Mangomaster1 Dec 23 '22 at 23:43
  • You can, you'd have to change your code, but `B` is a different type than `B`. The other option is to use reflection. Call `GetType` on `this` and then query whether it's a generic type, and what whether it's a `B` and what type `T` is – Flydog57 Dec 23 '22 at 23:47
  • That I can do, I've already found a stack overflow question talking about how to CHECK if it is of a certain generic type... but I do not know how to properly convert... I tried Convert.ChangeType but it wasn't successful – 1Mangomaster1 Dec 23 '22 at 23:51
  • The interface might be a good, altho weird looking solution... but seems like my best hope so I will do that, thank you! – 1Mangomaster1 Dec 24 '22 at 00:02
  • You don't need to _convert_ it to the `B` type; it already is an object of that type. What you can't do is assigned it to a variable of that type without an explicit cast – Flydog57 Dec 24 '22 at 00:04