Home > Blockchain >  Why bother casting the return value since the type has been specified when calling the function?
Why bother casting the return value since the type has been specified when calling the function?

Time:08-25

I am learning Editor Script of Unity recently, and I come across a piece of code in Unity Manual like this:

EditorWindowTest window  = (EditorWindowTest)EditorWindow.GetWindow(typeof(EditorWindowTest), true, "My Empty Window");

I don't know why bother casting the result with (EditorWindowTest) again since the type has been specified in the parameter field of GetWindow().

Thanks in advance :)

CodePudding user response:

There are multiple overloads of the enter image description here

When using one of the generic overloads of the GetWindow method, you don't need to do any manual casting, since the method already knows at compile time the exact type of the window and returns an instance of that type directly.

enter image description here

The generic variants should be used when possible, because it makes the code safer by removing the need for casting at runtime, which could cause exceptions.

CodePudding user response:

If you closely look, GetWindow's return type is EditorWindow. Not the EditorWindowTest, so typecasting makes sense.

https://docs.unity3d.com/ScriptReference/EditorWindow.GetWindow.html

  • Related