Generic function: cast Node as T doesn't work

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Firefly90

Hey everyone, I am trying to make a custom generic function that will read a text field as int. Since I don’t know the exact node type, I use something like this:

private int readIntField <T> (String nodeName, int defaultVal)
{
    T intNode = (T)this.FindNode(nodeName);
    int ret = defaultVal;
    Int32.TryParse(intNode.Text, out ret);
    return ret;
}

It gives an error “Cannot covner Godot.Node to T”

I am not suire if this is a Godot problem, or a C# problem (I am only starting to learn it). Please help.

:bust_in_silhouette: Reply From: AFE-GmdG

FindNode will give you a instance of a Node Class or of a class that is derived from Node.
The generic type T is unspecified. But the Method Signature has to be specified at compile time so this is not possible.
But I suspect you don’t need a generic method at all. Replace

T intNode = (T)this.FindNode(nodeName);

with

var intNode = FindNode(nodeName);
if (intNode === null) return defaultVal;

Since on Node there is no property “Text” you must have a derived class of Node that defines this property - so all you have to do is to try to cast your found node as the type with the Text property:

var nodeWithTextProperty = intNode as ClassDerivedFromNodeWithTextProperty;
if (nodeWithTextProperty == null) return defaultVal;

int ret;
if (Int32.TryParse(nodeWithTextProperty.Text, out ret)) return ret;

return defaultVal;