Reference Lifetimes
Lesson 40 of 48 in Coddy's GDScript for C# Developers course.
Ordinary .NET objects use tracing garbage collection; C# using and IDisposable address resource cleanup rather than forcing collection. Godot RefCounted objects use reference counting and do not automatically reclaim strong cycles. WeakRef observes without retaining its target. Clearing one reference does not destroy an object still held by another. Node lifetime is separate from RefCounted data lifetime. No manual free is needed for these data objects. The C# example uses KeepAlive to guarantee the strong reference remains live through the weak-reference observation.
Complete C# comparison. Compile all listed C# files together; Program.Main is the entry point.
C# file DemoItem.cs:
public class DemoItem {}C# file Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
public static class Program {
public static void Main() {
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
var a=new DemoItem();var weak=new WeakReference(a);var b=a;a=null;Console.WriteLine(Object.ReferenceEquals(weak.Target,b));GC.KeepAlive(b);
}
}C# output:
TrueGDScript example file main.gd:
extends Node
func _ready() -> void:
var a: RefCounted = RefCounted.new()
var weak: WeakRef = weakref(a)
var b: RefCounted = a
a = null
print(weak.get_ref() == b)GDScript output:
trueChallenge
EasyImplement OwnedNote(text:String) and static NoteViews.label(note:OwnedNote)->String. Return missing for null; otherwise return note.text. Solve creates a note for a string input, or passes null. Do not manually free RefCounted instances.
Input is one JSON array on stdin. The locked main parses it, calls the public APIs and prints result= followed by the returned text and a newline. No helper should print. Independent fixed probes verify required API behavior before the input case; they do not enforce implementation style.
Your code goes in owned_note.gd, note_views.gd, exercise.gd. main.gd holds the supplied input/output code and cannot be edited. Keep each class_name type in its named file.
Try it yourself
extends Node
func contract_ok(data: Array) -> bool:
var original: OwnedNote = OwnedNote.new("a")
var alias: OwnedNote = original
original = null
if NoteViews.label(alias) != "a" or NoteViews.label(null) != "missing": return false
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in GDScript for C# Developers
1Scripts and Scalar Values
Run Script FilesText and CommentsBindings and TypesInteger ArithmeticBoolean ResultsRecap: Stock Label2Flow and Functions
Branches and ValuesPattern MatchingLoops and RangesTyped FunctionsDefault ArgumentsRecap: Command Count5Objects and State
Scripts as ClassesInitializationInstance MethodsRecap: Independent BasketsProperty Setters8Boundaries and Lifetimes
Named Integer StatesNull and Type TestsSorting CopiesReference LifetimesRecap: Sorted TotalsRecap: Ordered CommandsPractice on your own: Online GDScript compiler