0

Hi I have the following extension method

    public static T[] GetComponentsOfType<T>(this GameObject source) where T : MonoBehaviour
    {
        Component[] matchingComponents = source.GetComponents<Component>().Where(comp => comp is T).ToArray();
        T[] castedComponents = new T[matchingComponents.Length];
        for (int i = 0; i < matchingComponents.Length; i++)
        {
            castedComponents[i] = (T) matchingComponents[i];
        }
        return castedComponents;
    }

Which works completely fine however I tried to shorten it by just a single line

 return (T[]) source.GetComponents<Component>().OfType<T>().Cast<Component>().ToArray();

And apparently this line fails to cast the Component[] to T[] but when I cast each element separately it works (the first example). Why is that ?

3
  • 1
    Well yes - if you've created a Component[], that isn't a FooComponent[] or whatever T is. Why not just use OfType<T>().ToArray()? Why are you calling Cast<Component>()? Commented Dec 2, 2016 at 11:20
  • 1
    Cast<Component>() doesn't make sense. If you want T's, why cast it to Component again? Commented Dec 2, 2016 at 11:20
  • Resharper made me do it @JonSkeet :) Commented Dec 2, 2016 at 11:25

2 Answers 2

2

You can write:

source.GetComponents<Component>().OfType<T>().ToArray();

To do it in one line.

The cast fails because you are casting two types that do not match and Array of component to and array of T and that is invalid.

Sign up to request clarification or add additional context in comments.

1 Comment

What do you expect the Select to do?
2

You should make use of the OfType<> only. In your solution, you are it back to Component, which can't be cast to T[], so thats the problem.

The OfType<> already casts it. It's like a substitute for Where(item => item is T).Cast<T>()

return source.GetComponents<Component>().OfType<T>().ToArray();

2 Comments

Indeed return source.GetComponents<Component>().OfType<T>().ToArray(); is completely enough for the task thank you for the quick response !
@JeroenvanLangen: But you've stlil got the actual cast operator (T[]). That's unnecessary, as the return type of ToArray() will already be T[].

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.