Search code examples
c#unity-game-enginecastinggeneric-type-argument

Casting Generic Types - Why does a direct cast with parenthesis "()" give a compile-error, but casting with the "as"-keyword works?


I needed to cast a generic type deriving from UnityEngine.Object into UnityEngine.AudioClip, but I was having this error all the time:

Error Message:

error CS0030: Cannot convert type 'T[]' to 'UnityEngine.AudioClip[]'

And I was baffled, cause AudioClip derives from Object, so it shouldn't be an issue to cast to it.

So the Example Code 1 below is how my code was when I got the error. Then I solved the error by changing the code to the one in Example Code 2.

So my question is:

Why did a direct cast (ie. using parenthesis) NOT work, but casting using the as-keyword did?

I want to understand why Example Code 2 works. I've looked at the "Direct casting vs 'as' operator?"-answer, but I don't understand how that would be related to this issue. So any help or explanation as to why this works the way it does would be really appreciated.


Example Code 1: Direct Cast (ie. using Parenthesis)

private void UpdateAudioClipsOnDragAndDrop<T>(T[] draggedObjects) where T : UnityEngine.Object
{
    audioClips = (AudioClip[])draggedObjects;
}

Example Code 2: Cast using the "as"-keyword

private void UpdateAudioClipsOnDragAndDrop<T>(T[] draggedObjects) where T : UnityEngine.Object
{
    audioClips = draggedObjects as AudioClip[];
}

Here's also a Screenshot of the Error in Visual Studio


Solution

  • In both cases you're casting down the inheritance tree, so it cannot be done implicitly as you and compiler doesn't know what type of object is being passed as type of T.

    In the first case with direct casting you're saying to compiler that it HAS to be the type of AudioClip[] and in the second that it MIGHT be - if it's not, then null will be the result.

    You can give a hint to compiler as you already do with the use of where keyword and specifying the class of T, so that even the first case will be non problematic to the compiler.