I have a list (called Within
), and it contains objects of type GameObject
. GameObject
is a parent class to many others, including Dog
and Ball
. I want to make a method that returns true if Within contains any object of type Ball
, but I don't know how to do this.
I've tried using Count<>
, Any<>
, Find<>
and a few other methods provided within C#, but I couldn't get them to work.
public bool DetectBall(List<GameObject> Within) { //if Within contains any object of type ball: { return true; } }
To determine whether an object is a specific type, you can use your language's type comparison keyword or construct. For example, you can use the TypeOf… Is construct in Visual Basic or the is keyword in C#. The GetType method is inherited by all types that derive from Object.
You can check object type in Java by using the instanceof keyword. Determining object type is important if you're processing a collection such as an array that contains more than one type of object. For example, you might have an array with string and integer representations of numbers.
You can use the Enumerable. Where extension method: var matches = myList.
if (within.OfType<Ball>().Any())
The generic parameter of all LINQ methods except Cast<T>()
and OfType<T>()
is used to allow the method call to compile and must be compatible with the type of the list (or for a covariant cast). They cannot be used to filter by type.
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