.. _doc_c_sharp_differences: C# API differences to GDScript ============================== This is a (incomplete) list of API differences between C# and GDScript. General differences ------------------- As explained in the :ref:`doc_c_sharp`, C# generally uses ``PascalCase`` instead of the ``snake_case`` used in GDScript and C++. Global scope ------------ Global functions and some constants had to be moved to classes, since C# does not allow declaring them in namespaces. Most global constants were moved to their own enums. Constants ^^^^^^^^^ In C#, only primitive types can be constant. For example, the ``TAU`` constant is replaced by the ``Mathf.Tau`` constant, but the ``Vector2.RIGHT`` constant is replaced by the ``Vector2.Right`` read-only property. This behaves similarly to a constant, but can't be used in some contexts like ``switch`` statements. Global enum constants were moved to their own enums. For example, ``ERR_*`` constants were moved to the ``Error`` enum. Special cases: ======================= =========================================================== GDScript C# ======================= =========================================================== ``TYPE_*`` ``Variant.Type`` enum ``OP_*`` ``Variant.Operator`` enum ======================= =========================================================== Math functions ^^^^^^^^^^^^^^ Math global functions, like ``abs``, ``acos``, ``asin``, ``atan`` and ``atan2``, are located under ``Mathf`` as ``Abs``, ``Acos``, ``Asin``, ``Atan`` and ``Atan2``. The ``PI`` constant can be found as ``Mathf.Pi``. C# also provides static `System.Math`_ and `System.MathF`_ classes that may contain other useful mathematical operations. .. _System.Math: https://learn.microsoft.com/en-us/dotnet/api/system.math .. _System.MathF: https://learn.microsoft.com/en-us/dotnet/api/system.mathf Random functions ^^^^^^^^^^^^^^^^ Random global functions, like ``rand_range`` and ``rand_seed``, are located under ``GD``. Example: ``GD.RandRange`` and ``GD.RandSeed``. Consider using `System.Random`_ or, if you need cryptographically strong randomness, `System.Security.Cryptography.RandomNumberGenerator`_. .. _System.Random: https://learn.microsoft.com/en-us/dotnet/api/system.random .. _System.Security.Cryptography.RandomNumberGenerator: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator Other functions ^^^^^^^^^^^^^^^ Many other global functions like ``print`` and ``var_to_str`` are located under ``GD``. Example: ``GD.Print`` and ``GD.VarToStr``. Exceptions: ============================ ======================================================= GDScript C# ============================ ======================================================= ``weakref(obj)`` ``GodotObject.WeakRef(obj)`` ``instance_from_id(id)`` ``GodotObject.InstanceFromId(id)`` ``is_instance_id_valid(id)`` ``GodotObject.IsInstanceIdValid(id)`` ``is_instance_valid(obj)`` ``GodotObject.IsInstanceValid(obj)`` ============================ ======================================================= Tips ^^^^ Sometimes it can be useful to use the ``using static`` directive. This directive allows to access the members and nested types of a class without specifying the class name. Example: .. code-block:: csharp using static Godot.GD; public class Test { static Test() { Print("Hello"); // Instead of GD.Print("Hello"); } } Full list of equivalences ^^^^^^^^^^^^^^^^^^^^^^^^^ List of Godot's global scope functions and their equivalent in C#: =============================== ============================================================== GDScript C# =============================== ============================================================== abs Mathf.Abs absf Mathf.Abs absi Mathf.Abs acos Mathf.Acos asin Mathf.Asin atan Mathf.Atan atan2 Mathf.Atan2 bezier_derivative Mathf.BezierDerivative bezier_interpolate Mathf.BezierInterpolate bytes_to_var GD.BytesToVar bytes_to_var_with_objects GD.BytesToVarWithObjects ceil Mathf.Ceil ceilf Mathf.Ceil ceili Mathf.CeilToInt clamp Mathf.Clamp clampf Mathf.Clamp clampi Mathf.Clamp cos Mathf.Cos cosh Mathf.Cosh cubic_interpolate Mathf.CubicInterpolate cubic_interpoalte_angle Mathf.CubicInterpolateAngle cubic_interpolate_angle_in_time Mathf.CubicInterpolateInTime cubic_interpolate_in_time Mathf.CubicInterpolateAngleInTime db_to_linear Mathf.DbToLinear deg_to_rad Mathf.DegToRad ease Mathf.Ease error_string Error.ToString exp Mathf.Exp floor Mathf.Floor floorf Mathf.Floor floori Mathf.FloorToInt fmod operator % fposmod Mathf.PosMod hash GD.Hash instance_from_id GodotObject.InstanceFromId inverse_lerp Mathf.InverseLerp is_equal_approx Mathf.IsEqualApprox is_finite Mathf.IsFinite or `float.IsFinite`_ or `double.IsFinite`_ is_inf Mathf.IsInf or `float.IsInfinity`_ or `double.IsInfinity`_ is_instance_id_valid GodotObject.IsInstanceIdValid is_instance_valid GodotObject.IsInstanceValid is_nan Mathf.IsNaN or `float.IsNaN`_ or `double.IsNaN`_ is_same operator == or `object.ReferenceEquals`_ is_zero_approx Mathf.IsZeroApprox lerp Mathf.Lerp lerp_angle Mathf.LerpAngle lerpf Mathf.Lerp linear_to_db Mathf.LinearToDb log Mathf.Log max Mathf.Max maxf Mathf.Max maxi Mathf.Max min Mathf.Min minf Mathf.Min mini Mathf.Min move_toward Mathf.MoveToward nearest_po2 Mathf.NearestPo2 pingpong Mathf.PingPong posmod Mathf.PosMod pow Mathf.Pow print GD.Print print_rich GD.PrintRich print_verbose Use OS.IsStdoutVerbose and GD.Print printerr GD.PrintErr printraw GD.PrintRaw prints GD.PrintS printt GD.PrintT push_error GD.PushError push_warning GD.PushWarning rad_to_deg Mathf.RadToDeg rand_from_seed GD.RandFromSeed randf GD.Randf randf_range GD.RandRange randfn GD.Randfn randi GD.Randi randi_range GD.RandRange randomize GD.Randomize remap Mathf.Remap rid_allocate_id N/A rid_from_int64 N/A round Mathf.Round roundf Mathf.Round roundi Mathf.RoundToInt seed GD.Seed sign Mathf.Sign signf Mathf.Sign signi Mathf.Sign sin Mathf.Sin sinh Mathf.Sinh smoothstep Mathf.SmoothStep snapped Mathf.Snapped snappedf Mathf.Snapped snappedi Mathf.Snapped sqrt Mathf.Sqrt step_decimals Mathf.StepDecimals str Use `$ string interpolation`_ str_to_var GD.StrToVar tan Mathf.Tan tanh Mathf.Tanh typeof Variant.VariantType var_to_bytes GD.VarToBytes var_to_bytes_with_objects GD.VarToBytesWithObjects var_to_str GD.VarToStr weakref GodotObject.WeakRef wrap Mathf.Wrap wrapf Mathf.Wrap wrapi Mathf.Wrap =============================== ============================================================== .. _$ string interpolation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated .. _double.IsFinite: https://learn.microsoft.com/en-us/dotnet/api/system.double.isfinite .. _double.IsInfinity: https://learn.microsoft.com/en-us/dotnet/api/system.double.isinfinity .. _double.IsNaN: https://learn.microsoft.com/en-us/dotnet/api/system.double.isnan .. _float.IsFinite: https://learn.microsoft.com/en-us/dotnet/api/system.single.isfinite .. _float.IsInfinity: https://learn.microsoft.com/en-us/dotnet/api/system.single.isinfinity .. _float.IsNaN: https://learn.microsoft.com/en-us/dotnet/api/system.single.isnan .. _object.ReferenceEquals: https://learn.microsoft.com/en-us/dotnet/api/system.object.referenceequals List of GDScript utility functions and their equivalent in C#: ======================= ============================================================== GDScript C# ======================= ============================================================== assert `System.Diagnostics.Debug.Assert`_ char Use explicit conversion: ``(char)65`` convert GD.Convert dict_to_inst N/A get_stack `System.Environment.StackTrace`_ inst_to_dict N/A len N/A load GD.Load preload N/A print_debug N/A print_stack GD.Print(`System.Environment.StackTrace`_) range GD.Range or `System.Linq.Enumerable.Range`_ type_exists ClassDB.ClassExists(type) ======================= ============================================================== .. _System.Diagnostics.Debug.Assert: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.assert .. _System.Environment.StackTrace: https://learn.microsoft.com/en-us/dotnet/api/system.environment.stacktrace .. _System.Linq.Enumerable.Range: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.range ``preload``, as it works in GDScript, is not available in C#. Use ``GD.Load`` or ``ResourceLoader.Load`` instead. ``@export`` annotation ---------------------- Use the ``[Export]`` attribute instead of the GDScript ``@export`` annotation. This attribute can also be provided with optional :ref:`PropertyHint` and ``hintString`` parameters. Default values can be set by assigning a value. Example: .. code-block:: csharp using Godot; public partial class MyNode : Node { [Export] private NodePath _nodePath; [Export] private string _name = "default"; [Export(PropertyHint.Range, "0,100000,1000,or_greater")] private int _income; [Export(PropertyHint.File, "*.png,*.jpg")] private string _icon; } See also: :ref:`doc_c_sharp_exports`. ``signal`` keyword ------------------ Use the ``[Signal]`` attribute to declare a signal instead of the GDScript ``signal`` keyword. This attribute should be used on a `delegate`, whose name signature will be used to define the signal. The `delegate` must have the ``EventHandler`` suffix, an `event` will be generated in the class with the same name but without the suffix, use that event's name with ``EmitSignal``. .. code-block:: csharp [Signal] delegate void MySignalEventHandler(string willSendAString); See also: :ref:`doc_c_sharp_signals`. `@onready` annotation --------------------- GDScript has the ability to defer the initialization of a member variable until the ready function is called with `@onready` (cf. :ref:`doc_gdscript_onready_annotation`). For example: .. code-block:: gdscript @onready var my_label = get_node("MyLabel") However C# does not have this ability. To achieve the same effect you need to do this. .. code-block:: csharp private Label _myLabel; public override void _Ready() { _myLabel = GetNode