Menu
CoddyTech

Property Setters

Lesson 26 of 48 in Coddy's GDScript for C# Developers course.

C# properties often store their value in a separate backing field. GDScript get/set blocks are attached to a variable declaration. In Godot 4 ordinary assignment invokes the setter even inside the same class, but assigning that property from its own setter accesses its underlying value instead of recursively invoking the setter. Initialization has special rules, so choose a valid initial value. A leading underscore is a convention in GDScript, not C# private access enforcement.

Complete C# comparison. Compile all listed C# files together; Program.Main is the entry point.

C# file DemoBadge.cs:

public class DemoBadge { private string text=""; public string Text { get{return text;} set{text=value.ToUpperInvariant();} } }

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 b=new DemoBadge();b.Text="go";Console.WriteLine(b.Text);
}
}

C# output:

GO

GDScript example file demo_badge.gd:

class_name DemoBadge
extends RefCounted
var text: String = "":
	set(value):
		text = value.to_upper()

GDScript example file main.gd:

extends Node

func _ready() -> void:
	var badge: DemoBadge = DemoBadge.new()
	badge.text = "go"
	print(badge.text)

GDScript output:

GO
challenge icon

Challenge

Easy

Implement LimitGauge.level:int with a setter clamping every assignment to 0..100. Initial value is zero. Solve assigns the input then returns level.

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 limit_gauge.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 gauge: LimitGauge = LimitGauge.new()
	gauge.level = -1
	if gauge.level != 0: return false
	gauge.level = 101
	if gauge.level != 100: return false
	gauge.level = 7
	if gauge.level != 7: 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in GDScript for C# Developers

Practice on your own: Online GDScript compiler