c_sharp_differences.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. .. _doc_c_sharp_differences:
  2. C# API differences to GDScript
  3. ==============================
  4. This is a (incomplete) list of API differences between C# and GDScript.
  5. General differences
  6. -------------------
  7. As explained in the :ref:`doc_c_sharp`, C# generally uses ``PascalCase`` instead
  8. of the ``snake_case`` used in GDScript and C++.
  9. Global scope
  10. ------------
  11. Global functions and some constants had to be moved to classes, since C#
  12. does not allow declaring them in namespaces.
  13. Most global constants were moved to their own enums.
  14. Constants
  15. ^^^^^^^^^
  16. Global constants were moved to their own enums.
  17. For example, ``ERR_*`` constants were moved to the ``Error`` enum.
  18. Special cases:
  19. ======================= ===========================================================
  20. GDScript C#
  21. ======================= ===========================================================
  22. ``SPKEY`` ``GD.SpKey``
  23. ``TYPE_*`` ``Variant.Type`` enum
  24. ``OP_*`` ``Variant.Operator`` enum
  25. ======================= ===========================================================
  26. Math functions
  27. ^^^^^^^^^^^^^^
  28. Math global functions, like ``abs``, ``acos``, ``asin``, ``atan`` and ``atan2``, are
  29. located under ``Mathf`` as ``Abs``, ``Acos``, ``Asin``, ``Atan`` and ``Atan2``.
  30. The ``PI`` constant can be found as ``Mathf.Pi``.
  31. Random functions
  32. ^^^^^^^^^^^^^^^^
  33. Random global functions, like ``rand_range`` and ``rand_seed``, are located under ``GD``.
  34. Example: ``GD.RandRange`` and ``GD.RandSeed``.
  35. Other functions
  36. ^^^^^^^^^^^^^^^
  37. Many other global functions like ``print`` and ``var2str`` are located under ``GD``.
  38. Example: ``GD.Print`` and ``GD.Var2Str``.
  39. Exceptions:
  40. =========================== =======================================================
  41. GDScript C#
  42. =========================== =======================================================
  43. ``weakref(obj)`` ``Object.WeakRef(obj)``
  44. ``is_instance_valid(obj)`` ``Object.IsInstanceValid(obj)``
  45. =========================== =======================================================
  46. Tips
  47. ^^^^
  48. Sometimes it can be useful to use the ``using static`` directive. This directive allows
  49. to access the members and nested types of a class without specifying the class name.
  50. Example:
  51. .. code-block:: csharp
  52. using static Godot.GD;
  53. public class Test
  54. {
  55. static Test()
  56. {
  57. Print("Hello"); // Instead of GD.Print("Hello");
  58. }
  59. }
  60. Export keyword
  61. --------------
  62. Use the ``[Export]`` attribute instead of the GDScript ``export`` keyword.
  63. This attribute can also be provided with optional :ref:`PropertyHint<enum_@GlobalScope_PropertyHint>` and ``hintString`` parameters.
  64. Default values can be set by assigning a value.
  65. Example:
  66. .. code-block:: csharp
  67. using Godot;
  68. public class MyNode : Node
  69. {
  70. [Export]
  71. private NodePath _nodePath;
  72. [Export]
  73. private string _name = "default";
  74. [Export(PropertyHint.Range, "0,100000,1000,or_greater")]
  75. private int _income;
  76. [Export(PropertyHint.File, "*.png,*.jpg")]
  77. private string _icon;
  78. }
  79. Signal keyword
  80. --------------
  81. Use the ``[Signal]`` attribute to declare a signal instead of the GDScript ``signal`` keyword.
  82. This attribute should be used on a `delegate`, whose name signature will be used to define the signal.
  83. .. code-block:: csharp
  84. [Signal]
  85. delegate void MySignal(string willSendsAString);
  86. See also: :ref:`doc_c_sharp_signals`.
  87. `onready` keyword
  88. -----------------
  89. GDScript has the ability to defer the initialization of a member variable until the ready function
  90. is called with `onready` (cf. :ref:`doc_gdscript_onready_keyword`).
  91. For example:
  92. .. code-block:: gdscript
  93. onready var my_label = get_node("MyLabel")
  94. However C# does not have this ability. To achieve the same effect you need to do this.
  95. .. code-block:: csharp
  96. private Label _myLabel;
  97. public override void _Ready()
  98. {
  99. _myLabel = GetNode<Label>("MyLabel");
  100. }
  101. Singletons
  102. ----------
  103. Singletons are available as static classes rather than using the singleton pattern.
  104. This is to make code less verbose than it would be with an ``Instance`` property.
  105. Example:
  106. .. code-block:: csharp
  107. Input.IsActionPressed("ui_down")
  108. However, in some very rare cases this is not enough. For example, you may want
  109. to access a member from the base class ``Godot.Object``, like ``Connect``.
  110. For such use cases we provide a static property named ``Singleton`` that returns
  111. the singleton instance. The type of this instance is ``Godot.Object``.
  112. Example:
  113. .. code-block:: csharp
  114. Input.Singleton.Connect("joy_connection_changed", this, nameof(Input_JoyConnectionChanged));
  115. String
  116. ------
  117. Use ``System.String`` (``string``). Most of Godot's String methods are
  118. provided by the ``StringExtensions`` class as extension methods.
  119. Example:
  120. .. code-block:: csharp
  121. string upper = "I LIKE SALAD FORKS";
  122. string lower = upper.ToLower();
  123. There are a few differences, though:
  124. * ``erase``: Strings are immutable in C#, so we cannot modify the string
  125. passed to the extension method. For this reason, ``Erase`` was added as an
  126. extension method of ``StringBuilder`` instead of string.
  127. Alternatively, you can use ``string.Remove``.
  128. * ``IsSubsequenceOf``/``IsSubsequenceOfi``: An additional method is provided,
  129. which is an overload of ``IsSubsequenceOf``, allowing you to explicitly specify
  130. case sensitivity:
  131. .. code-block:: csharp
  132. str.IsSubsequenceOf("ok"); // Case sensitive
  133. str.IsSubsequenceOf("ok", true); // Case sensitive
  134. str.IsSubsequenceOfi("ok"); // Case insensitive
  135. str.IsSubsequenceOf("ok", false); // Case insensitive
  136. * ``Match``/``Matchn``/``ExprMatch``: An additional method is provided besides
  137. ``Match`` and ``Matchn``, which allows you to explicitly specify case sensitivity:
  138. .. code-block:: csharp
  139. str.Match("*.txt"); // Case sensitive
  140. str.ExprMatch("*.txt", true); // Case sensitive
  141. str.Matchn("*.txt"); // Case insensitive
  142. str.ExprMatch("*.txt", false); // Case insensitive
  143. Basis
  144. -----
  145. Structs cannot have parameterless constructors in C#. Therefore, ``new Basis()``
  146. initializes all primitive members to their default value. Use ``Basis.Identity``
  147. for the equivalent of ``Basis()`` in GDScript and C++.
  148. The following method was converted to a property with a different name:
  149. ==================== ==============================================================
  150. GDScript C#
  151. ==================== ==============================================================
  152. ``get_scale()`` ``Scale``
  153. ==================== ==============================================================
  154. Transform2D
  155. -----------
  156. Structs cannot have parameterless constructors in C#. Therefore, ``new Transform2D()``
  157. initializes all primitive members to their default value.
  158. Please use ``Transform2D.Identity`` for the equivalent of ``Transform2D()`` in GDScript and C++.
  159. The following methods were converted to properties with their respective names changed:
  160. ==================== ==============================================================
  161. GDScript C#
  162. ==================== ==============================================================
  163. ``get_rotation()`` ``Rotation``
  164. ``get_scale()`` ``Scale``
  165. ==================== ==============================================================
  166. Plane
  167. -----
  168. The following method was converted to a property with a *slightly* different name:
  169. ================ ==================================================================
  170. GDScript C#
  171. ================ ==================================================================
  172. ``center()`` ``Center``
  173. ================ ==================================================================
  174. Rect2
  175. -----
  176. The following field was converted to a property with a *slightly* different name:
  177. ================ ==================================================================
  178. GDScript C#
  179. ================ ==================================================================
  180. ``end`` ``End``
  181. ================ ==================================================================
  182. The following method was converted to a property with a different name:
  183. ================ ==================================================================
  184. GDScript C#
  185. ================ ==================================================================
  186. ``get_area()`` ``Area``
  187. ================ ==================================================================
  188. Quat
  189. ----
  190. Structs cannot have parameterless constructors in C#. Therefore, ``new Quat()``
  191. initializes all primitive members to their default value.
  192. Please use ``Quat.Identity`` for the equivalent of ``Quat()`` in GDScript and C++.
  193. The following methods were converted to a property with a different name:
  194. ===================== =============================================================
  195. GDScript C#
  196. ===================== =============================================================
  197. ``length()`` ``Length``
  198. ``length_squared()`` ``LengthSquared``
  199. ===================== =============================================================
  200. Array
  201. -----
  202. *This is temporary. PoolArrays will need their own types to be used the way they are meant to.*
  203. ===================== ==============================================================
  204. GDScript C#
  205. ===================== ==============================================================
  206. ``Array`` ``Godot.Collections.Array``
  207. ``PoolIntArray`` ``int[]``
  208. ``PoolByteArray`` ``byte[]``
  209. ``PoolFloatArray`` ``float[]``
  210. ``PoolStringArray`` ``String[]``
  211. ``PoolColorArray`` ``Color[]``
  212. ``PoolVector2Array`` ``Vector2[]``
  213. ``PoolVector3Array`` ``Vector3[]``
  214. ===================== ==============================================================
  215. ``Godot.Collections.Array<T>`` is a type-safe wrapper around ``Godot.Collections.Array``.
  216. Use the ``Godot.Collections.Array<T>(Godot.Collections.Array)`` constructor to create one.
  217. Dictionary
  218. ----------
  219. Use ``Godot.Collections.Dictionary``.
  220. ``Godot.Collections.Dictionary<T>`` is a type-safe wrapper around ``Godot.Collections.Dictionary``.
  221. Use the ``Godot.Collections.Dictionary<T>(Godot.Collections.Dictionary)`` constructor to create one.
  222. Variant
  223. -------
  224. ``System.Object`` (``object``) is used instead of ``Variant``.
  225. Communicating with other scripting languages
  226. --------------------------------------------
  227. This is explained extensively in :ref:`doc_cross_language_scripting`.
  228. Yield
  229. -----
  230. Something similar to GDScript's ``yield`` with a single parameter can be achieved with
  231. C#'s `yield keyword <https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/yield>`_.
  232. The equivalent of yield on signal can be achieved with async/await and ``Godot.Object.ToSignal``.
  233. Example:
  234. .. code-block:: csharp
  235. await ToSignal(timer, "timeout");
  236. GD.Print("After timeout");
  237. Other differences
  238. -----------------
  239. ``preload``, as it works in GDScript, is not available in C#.
  240. Use ``GD.Load`` or ``ResourceLoader.Load`` instead.
  241. Other differences:
  242. ================ ==================================================================
  243. GDScript C#
  244. ================ ==================================================================
  245. ``Color8`` ``Color.Color8``
  246. ``is_inf`` ``float.IsInfinity``
  247. ``is_nan`` ``float.IsNaN``
  248. ``dict2inst`` TODO
  249. ``inst2dict`` TODO
  250. ================ ==================================================================