c_sharp_differences.rst 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  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. In C#, only primitive types can be constant. For example, the ``TAU`` constant
  17. is replaced by the ``Mathf.Tau`` constant, but the ``Vector2.RIGHT`` constant
  18. is replaced by the ``Vector2.Right`` read-only property. This behaves similarly
  19. to a constant, but can't be used in some contexts like ``switch`` statements.
  20. Global enum constants were moved to their own enums.
  21. For example, ``ERR_*`` constants were moved to the ``Error`` enum.
  22. Special cases:
  23. ======================= ===========================================================
  24. GDScript C#
  25. ======================= ===========================================================
  26. ``TYPE_*`` ``Variant.Type`` enum
  27. ``OP_*`` ``Variant.Operator`` enum
  28. ======================= ===========================================================
  29. Math functions
  30. ^^^^^^^^^^^^^^
  31. Math global functions, like ``abs``, ``acos``, ``asin``, ``atan`` and ``atan2``, are
  32. located under ``Mathf`` as ``Abs``, ``Acos``, ``Asin``, ``Atan`` and ``Atan2``.
  33. The ``PI`` constant can be found as ``Mathf.Pi``.
  34. C# also provides static `System.Math`_ and `System.MathF`_ classes that may
  35. contain other useful mathematical operations.
  36. .. _System.Math: https://learn.microsoft.com/en-us/dotnet/api/system.math
  37. .. _System.MathF: https://learn.microsoft.com/en-us/dotnet/api/system.mathf
  38. Random functions
  39. ^^^^^^^^^^^^^^^^
  40. Random global functions, like ``rand_range`` and ``rand_seed``, are located under ``GD``.
  41. Example: ``GD.RandRange`` and ``GD.RandSeed``.
  42. Consider using `System.Random`_ or, if you need cryptographically strong randomness,
  43. `System.Security.Cryptography.RandomNumberGenerator`_.
  44. .. _System.Random: https://learn.microsoft.com/en-us/dotnet/api/system.random
  45. .. _System.Security.Cryptography.RandomNumberGenerator: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.randomnumbergenerator
  46. Other functions
  47. ^^^^^^^^^^^^^^^
  48. Many other global functions like ``print`` and ``var_to_str`` are located under ``GD``.
  49. Example: ``GD.Print`` and ``GD.VarToStr``.
  50. Exceptions:
  51. =========================== =======================================================
  52. GDScript C#
  53. =========================== =======================================================
  54. ``weakref(obj)`` ``GodotObject.WeakRef(obj)``
  55. ``is_instance_valid(obj)`` ``GodotObject.IsInstanceValid(obj)``
  56. =========================== =======================================================
  57. Tips
  58. ^^^^
  59. Sometimes it can be useful to use the ``using static`` directive. This directive allows
  60. to access the members and nested types of a class without specifying the class name.
  61. Example:
  62. .. code-block:: csharp
  63. using static Godot.GD;
  64. public class Test
  65. {
  66. static Test()
  67. {
  68. Print("Hello"); // Instead of GD.Print("Hello");
  69. }
  70. }
  71. ``@export`` annotation
  72. ----------------------
  73. Use the ``[Export]`` attribute instead of the GDScript ``@export`` annotation.
  74. This attribute can also be provided with optional :ref:`PropertyHint<enum_@GlobalScope_PropertyHint>` and ``hintString`` parameters.
  75. Default values can be set by assigning a value.
  76. Example:
  77. .. code-block:: csharp
  78. using Godot;
  79. public partial class MyNode : Node
  80. {
  81. [Export]
  82. private NodePath _nodePath;
  83. [Export]
  84. private string _name = "default";
  85. [Export(PropertyHint.Range, "0,100000,1000,or_greater")]
  86. private int _income;
  87. [Export(PropertyHint.File, "*.png,*.jpg")]
  88. private string _icon;
  89. }
  90. See also: :ref:`doc_c_sharp_exports`.
  91. ``signal`` keyword
  92. ------------------
  93. Use the ``[Signal]`` attribute to declare a signal instead of the GDScript ``signal`` keyword.
  94. This attribute should be used on a `delegate`, whose name signature will be used to define the signal.
  95. 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``.
  96. .. code-block:: csharp
  97. [Signal]
  98. delegate void MySignalEventHandler(string willSendAString);
  99. See also: :ref:`doc_c_sharp_signals`.
  100. `@onready` annotation
  101. ---------------------
  102. GDScript has the ability to defer the initialization of a member variable until the ready function
  103. is called with `@onready` (cf. :ref:`doc_gdscript_onready_annotation`).
  104. For example:
  105. .. code-block:: gdscript
  106. @onready var my_label = get_node("MyLabel")
  107. However C# does not have this ability. To achieve the same effect you need to do this.
  108. .. code-block:: csharp
  109. private Label _myLabel;
  110. public override void _Ready()
  111. {
  112. _myLabel = GetNode<Label>("MyLabel");
  113. }
  114. Singletons
  115. ----------
  116. Singletons are available as static classes rather than using the singleton pattern.
  117. This is to make code less verbose than it would be with an ``Instance`` property.
  118. Example:
  119. .. code-block:: csharp
  120. Input.IsActionPressed("ui_down")
  121. However, in some very rare cases this is not enough. For example, you may want
  122. to access a member from the base class ``GodotObject``, like ``Connect``.
  123. For such use cases we provide a static property named ``Singleton`` that returns
  124. the singleton instance. The type of this instance is ``GodotObject``.
  125. Example:
  126. .. code-block:: csharp
  127. Input.Singleton.JoyConnectionChanged += Input_JoyConnectionChanged;
  128. String
  129. ------
  130. Use ``System.String`` (``string``). Most of Godot's String methods have an
  131. equivalent in ``System.String`` or are provided by the ``StringExtensions``
  132. class as extension methods.
  133. Example:
  134. .. code-block:: csharp
  135. string text = "Get up!";
  136. string[] bigrams = text.Bigrams(); // ["Ge", "et", "t ", " u", "up", "p!"]
  137. Strings are immutable in .NET, so all methods that manipulate a string don't
  138. modify the original string and return a newly created string with the
  139. modifications applied. To avoid creating multiple string allocations consider
  140. using a `StringBuilder`_.
  141. List of Godot's String methods and their equivalent in C#:
  142. ======================= ==============================================================
  143. GDScript C#
  144. ======================= ==============================================================
  145. begins_with `string.StartsWith`_
  146. bigrams StringExtensions.Bigrams
  147. bin_to_int StringExtensions.BinToInt
  148. c_escape StringExtensions.CEscape
  149. c_unescape StringExtensions.CUnescape
  150. capitalize StringExtensions.Capitalize
  151. casecmp_to StringExtensions.CasecmpTo or StringExtensions.CompareTo (Consider using `string.Equals`_ or `string.Compare`_)
  152. chr N/A
  153. contains `string.Contains`_
  154. count StringExtensions.Count (Consider using `RegEx`_)
  155. countn StringExtensions.CountN (Consider using `RegEx`_)
  156. dedent StringExtensions.Dedent
  157. ends_with `string.EndsWith`_
  158. find StringExtensions.Find (Consider using `string.IndexOf`_ or `string.IndexOfAny`_)
  159. findn StringExtensions.FindN (Consider using `string.IndexOf`_ or `string.IndexOfAny`_)
  160. format Use `$ string interpolation`_
  161. get_base_dir StringExtensions.GetBaseDir
  162. get_basename StringExtensions.GetBaseName
  163. get_extension StringExtensions.GetExtension
  164. get_file StringExtensions.GetFile
  165. get_slice N/A
  166. get_slice_count N/A
  167. get_slicec N/A
  168. hash StringExtensions.Hash (Consider using `object.GetHashCode`_ unless you need to guarantee the same behavior as in GDScript)
  169. hex_to_int StringExtensions.HexToInt (Consider using `int.Parse`_ or `long.Parse`_ with `System.Globalization.NumberStyles.HexNumber`_)
  170. humanize_size N/A
  171. indent StringExtensions.Indent
  172. insert `string.Insert`_ (Consider using `StringBuilder`_ to manipulate strings)
  173. is_absolute_path StringExtensions.IsAbsolutePath
  174. is_empty `string.IsNullOrEmpty`_ or `string.IsNullOrWhiteSpace`_
  175. is_relative_path StringExtensions.IsRelativePath
  176. is_subsequence_of StringExtensions.IsSubsequenceOf
  177. is_subsequence_ofn StringExtensions.IsSubsequenceOfN
  178. is_valid_filename StringExtensions.IsValidFileName
  179. is_valid_float StringExtensions.IsValidFloat (Consider using `float.TryParse`_ or `double.TryParse`_)
  180. is_valid_hex_number StringExtensions.IsValidHexNumber
  181. is_valid_html_color StringExtensions.IsValidHtmlColor
  182. is_valid_identifier StringExtensions.IsValidIdentifier
  183. is_valid_int StringExtensions.IsValidInt (Consider using `int.TryParse`_ or `long.TryParse`_)
  184. is_valid_ip_address StringExtensions.IsValidIPAddress
  185. join `string.Join`_
  186. json_escape StringExtensions.JSONEscape
  187. left StringExtensions.Left (Consider using `string.Substring`_ or `string.AsSpan`_)
  188. length `string.Length`_
  189. lpad `string.PadLeft`_
  190. lstrip `string.TrimStart`_
  191. match StringExtensions.Match (Consider using `RegEx`_)
  192. matchn StringExtensions.MatchN (Consider using `RegEx`_)
  193. md5_buffer StringExtensions.MD5Buffer (Consider using `System.Security.Cryptography.MD5.HashData`_)
  194. md5_text StringExtensions.MD5Text (Consider using `System.Security.Cryptography.MD5.HashData`_ with StringExtensions.HexEncode)
  195. naturalnocasecmp_to N/A (Consider using `string.Equals`_ or `string.Compare`_)
  196. nocasecmp_to StringExtensions.NocasecmpTo or StringExtensions.CompareTo (Consider using `string.Equals`_ or `string.Compare`_)
  197. num `float.ToString`_ or `double.ToString`_
  198. num_int64 `int.ToString`_ or `long.ToString`_
  199. num_scientific `float.ToString`_ or `double.ToString`_
  200. num_uint64 `uint.ToString`_ or `ulong.ToString`_
  201. pad_decimals StringExtensions.PadDecimals
  202. pad_zeros StringExtensions.PadZeros
  203. path_join StringExtensions.PathJoin
  204. repeat Use `string constructor`_ or a `StringBuilder`_
  205. replace `string.Replace`_ or `RegEx`_
  206. replacen StringExtensions.ReplaceN (Consider using `string.Replace`_ or `RegEx`_)
  207. rfind StringExtensions.RFind (Consider using `string.LastIndexOf`_ or `string.LastIndexOfAny`_)
  208. rfindn StringExtensions.RFindN (Consider using `string.LastIndexOf`_ or `string.LastIndexOfAny`_)
  209. right StringExtensions.Right (Consider using `string.Substring`_ or `string.AsSpan`_)
  210. rpad `string.PadRight`_
  211. rsplit N/A
  212. rstrip `string.TrimEnd`_
  213. sha1_buffer StringExtensions.SHA1Buffer (Consider using `System.Security.Cryptography.SHA1.HashData`_)
  214. sha1_text StringExtensions.SHA1Text (Consider using `System.Security.Cryptography.SHA1.HashData`_ with StringExtensions.HexEncode)
  215. sha256_buffer StringExtensions.SHA256Buffer (Consider using `System.Security.Cryptography.SHA256.HashData`_)
  216. sha256_text StringExtensions.SHA256Text (Consider using `System.Security.Cryptography.SHA256.HashData`_ with StringExtensions.HexEncode)
  217. similarity StringExtensions.Similarity
  218. simplify_path StringExtensions.SimplifyPath
  219. split StringExtensions.Split (Consider using `string.Split`_)
  220. split_floats StringExtensions.SplitFloat
  221. strip_edges StringExtensions.StripEdges (Consider using `string.Trim`_, `string.TrimStart`_ or `string.TrimEnd`_)
  222. strip_escapes StringExtensions.StripEscapes
  223. substr StringExtensions.Substr (Consider using `string.Substring`_ or `string.AsSpan`_)
  224. to_ascii_buffer StringExtensions.ToASCIIBuffer (Consider using `System.Text.Encoding.ASCII.GetBytes`_)
  225. to_camel_case StringExtensions.ToCamelCase
  226. to_float StringExtensions.ToFloat (Consider using `float.TryParse`_ or `double.TryParse`_)
  227. to_int StringExtensions.ToInt (Consider using `int.TryParse`_ or `long.TryParse`_)
  228. to_lower `string.ToLower`_
  229. to_pascal_case StringExtensions.ToPascalCase
  230. to_snake_case StringExtensions.ToSnakeCase
  231. to_upper `string.ToUpper`_
  232. to_utf16_buffer StringExtensions.ToUTF16Buffer (Consider using `System.Text.Encoding.UTF16.GetBytes`_)
  233. to_utf32_buffer StringExtensions.ToUTF32Buffer (Consider using `System.Text.Encoding.UTF32.GetBytes`_)
  234. to_utf8_buffer StringExtensions.ToUTF8Buffer (Consider using `System.Text.Encoding.UTF8.GetBytes`_)
  235. trim_prefix StringExtensions.TrimPrefix
  236. trim_suffix StringExtensions.TrimSuffix
  237. unicode_at `string[int]`_ indexer
  238. uri_decode StringExtensions.URIDecode (Consider using `System.Uri.UnescapeDataString`_)
  239. uri_encode StringExtensions.URIEncode (Consider using `System.Uri.EscapeDataString`_)
  240. validate_node_name StringExtensions.ValidateNodeName
  241. xml_escape StringExtensions.XMLEscape
  242. xml_unescape StringExtensions.XMLUnescape
  243. ======================= ==============================================================
  244. List of Godot's PackedByteArray methods that create a String and their C# equivalent:
  245. ========================= ==============================================================
  246. GDScript C#
  247. ========================= ==============================================================
  248. get_string_from_ascii StringExtensions.GetStringFromASCII (Consider using `System.Text.Encoding.ASCII.GetString`_)
  249. get_string_from_utf16 StringExtensions.GetStringFromUTF16 (Consider using `System.Text.Encoding.UTF16.GetString`_)
  250. get_string_from_utf32 StringExtensions.GetStringFromUTF32 (Consider using `System.Text.Encoding.UTF32.GetString`_)
  251. get_string_from_utf8 StringExtensions.GetStringFromUTF8 (Consider using `System.Text.Encoding.UTF8.GetString`_)
  252. hex_encode StringExtensions.HexEncode (Consider using `System.Convert.ToHexString`_)
  253. ========================= ==============================================================
  254. * .NET contains many path utility methods available under the
  255. `System.IO.Path`_
  256. class that can be used when not dealing with Godot paths (paths that start
  257. with ``res://`` or ``user://``)
  258. .. _$ string interpolation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
  259. .. _double.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.double.tostring
  260. .. _double.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse
  261. .. _float.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.single.tostring
  262. .. _float.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.single.tryparse
  263. .. _int.Parse: https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse
  264. .. _int.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tostring
  265. .. _int.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse
  266. .. _long.Parse: https://learn.microsoft.com/en-us/dotnet/api/system.int64.parse
  267. .. _long.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tostring
  268. .. _long.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse
  269. .. _uint.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tostring
  270. .. _ulong.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tostring
  271. .. _object.GetHashCode: https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode
  272. .. _RegEx: https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expressions
  273. .. _string constructor: https://learn.microsoft.com/en-us/dotnet/api/system.string.-ctor
  274. .. _string[int]: https://learn.microsoft.com/en-us/dotnet/api/system.string.chars
  275. .. _string.AsSpan: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.asspan
  276. .. _string.Compare: https://learn.microsoft.com/en-us/dotnet/api/system.string.compare
  277. .. _string.Contains: https://learn.microsoft.com/en-us/dotnet/api/system.string.contains
  278. .. _string.EndsWith: https://learn.microsoft.com/en-us/dotnet/api/system.string.endswith
  279. .. _string.Equals: https://learn.microsoft.com/en-us/dotnet/api/system.string.equals
  280. .. _string.IndexOf: https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof
  281. .. _string.IndexOfAny: https://learn.microsoft.com/en-us/dotnet/api/system.string.indexofany
  282. .. _string.Insert: https://learn.microsoft.com/en-us/dotnet/api/system.string.insert
  283. .. _string.IsNullOrEmpty: https://learn.microsoft.com/en-us/dotnet/api/system.string.isnullorempty
  284. .. _string.IsNullOrWhiteSpace: https://learn.microsoft.com/en-us/dotnet/api/system.string.isnullorwhitespace
  285. .. _string.Join: https://learn.microsoft.com/en-us/dotnet/api/system.string.join
  286. .. _string.LastIndexOf: https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexof
  287. .. _string.LastIndexOfAny: https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexofany
  288. .. _string.Length: https://learn.microsoft.com/en-us/dotnet/api/system.string.length
  289. .. _string.PadLeft: https://learn.microsoft.com/en-us/dotnet/api/system.string.padleft
  290. .. _string.PadRight: https://learn.microsoft.com/en-us/dotnet/api/system.string.padright
  291. .. _string.Replace: https://learn.microsoft.com/en-us/dotnet/api/system.string.replace
  292. .. _string.Split: https://learn.microsoft.com/en-us/dotnet/api/system.string.split
  293. .. _string.StartsWith: https://learn.microsoft.com/en-us/dotnet/api/system.string.startswith
  294. .. _string.Substring: https://learn.microsoft.com/en-us/dotnet/api/system.string.substring
  295. .. _string.Trim: https://learn.microsoft.com/en-us/dotnet/api/system.string.trim
  296. .. _string.TrimEnd: https://learn.microsoft.com/en-us/dotnet/api/system.string.trimend
  297. .. _string.TrimStart: https://learn.microsoft.com/en-us/dotnet/api/system.string.trimstart
  298. .. _string.ToLower: https://learn.microsoft.com/en-us/dotnet/api/system.string.tolower
  299. .. _string.ToUpper: https://learn.microsoft.com/en-us/dotnet/api/system.string.toupper
  300. .. _StringBuilder: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder
  301. .. _System.Convert.ToHexString: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring
  302. .. _System.Globalization.NumberStyles.HexNumber: https://learn.microsoft.com/en-us/dotnet/api/system.globalization.numberstyles#system-globalization-numberstyles-hexnumber
  303. .. _System.IO.Path: https://learn.microsoft.com/en-us/dotnet/api/system.io.path
  304. .. _System.Security.Cryptography.MD5.HashData: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5.hashdata
  305. .. _System.Security.Cryptography.SHA1.HashData: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha1.hashdata
  306. .. _System.Security.Cryptography.SHA256.HashData: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata
  307. .. _System.Text.Encoding.ASCII.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.asciiencoding.getbytes
  308. .. _System.Text.Encoding.ASCII.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.asciiencoding.getstring
  309. .. _System.Text.Encoding.UTF16.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.unicodeencoding.getbytes
  310. .. _System.Text.Encoding.UTF16.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.unicodeencoding.getstring
  311. .. _System.Text.Encoding.UTF32.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf32encoding.getbytes
  312. .. _System.Text.Encoding.UTF32.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf32encoding.getstring
  313. .. _System.Text.Encoding.UTF8.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf8encoding.getbytes
  314. .. _System.Text.Encoding.UTF8.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf8encoding.getstring
  315. .. _System.Uri.EscapeDataString: https://learn.microsoft.com/en-us/dotnet/api/system.uri.escapedatastring
  316. .. _System.Uri.UnescapeDataString: https://learn.microsoft.com/en-us/dotnet/api/system.uri.unescapedatastring
  317. Basis
  318. -----
  319. Structs cannot have parameterless constructors in C#. Therefore, ``new Basis()``
  320. initializes all primitive members to their default value. Use ``Basis.Identity``
  321. for the equivalent of ``Basis()`` in GDScript and C++.
  322. The following method was converted to a property with a different name:
  323. ==================== ==============================================================
  324. GDScript C#
  325. ==================== ==============================================================
  326. ``get_scale()`` ``Scale``
  327. ==================== ==============================================================
  328. Transform2D
  329. -----------
  330. Structs cannot have parameterless constructors in C#. Therefore, ``new Transform2D()``
  331. initializes all primitive members to their default value.
  332. Please use ``Transform2D.Identity`` for the equivalent of ``Transform2D()`` in GDScript and C++.
  333. The following methods were converted to properties with their respective names changed:
  334. ==================== ==============================================================
  335. GDScript C#
  336. ==================== ==============================================================
  337. ``get_rotation()`` ``Rotation``
  338. ``get_scale()`` ``Scale``
  339. ==================== ==============================================================
  340. Rect2
  341. -----
  342. The following field was converted to a property with a *slightly* different name:
  343. ================ ==================================================================
  344. GDScript C#
  345. ================ ==================================================================
  346. ``end`` ``End``
  347. ================ ==================================================================
  348. The following method was converted to a property with a different name:
  349. ================ ==================================================================
  350. GDScript C#
  351. ================ ==================================================================
  352. ``get_area()`` ``Area``
  353. ================ ==================================================================
  354. Quaternion
  355. ----------
  356. Structs cannot have parameterless constructors in C#. Therefore, ``new Quaternion()``
  357. initializes all primitive members to their default value.
  358. Please use ``Quaternion.Identity`` for the equivalent of ``Quaternion()`` in GDScript and C++.
  359. Color
  360. -----
  361. Structs cannot have parameterless constructors in C#. Therefore, ``new Color()``
  362. initializes all primitive members to their default value (which represents the transparent black color).
  363. Please use ``Colors.Black`` for the equivalent of ``Color()`` in GDScript and C++.
  364. The global ``Color8`` method to construct a Color from bytes is available as a static method
  365. in the Color type.
  366. The Color constants are available in the ``Colors`` static class as readonly properties.
  367. The following method was converted to a property with a different name:
  368. ==================== ==============================================================
  369. GDScript C#
  370. ==================== ==============================================================
  371. ``get_luminance()`` ``Luminance``
  372. ==================== ==============================================================
  373. The following method was converted to a method with a different name:
  374. ==================== ==============================================================
  375. GDScript C#
  376. ==================== ==============================================================
  377. ``html(String)`` ``FromHtml(ReadOnlySpan<char>)``
  378. ==================== ==============================================================
  379. The following methods are available as constructors:
  380. ==================== ==============================================================
  381. GDScript C#
  382. ==================== ==============================================================
  383. ``hex(int)`` ``Color(uint)``
  384. ``hex64(int)`` ``Color(ulong)``
  385. ==================== ==============================================================
  386. Array
  387. -----
  388. *This is temporary. PackedArrays will need their own types to be used the way they are meant to.*
  389. ====================== ==============================================================
  390. GDScript C#
  391. ====================== ==============================================================
  392. ``Array`` ``Godot.Collections.Array``
  393. ``PackedInt32Array`` ``int[]``
  394. ``PackedInt64Array`` ``long[]``
  395. ``PackedByteArray`` ``byte[]``
  396. ``PackedFloat32Array`` ``float[]``
  397. ``PackedFloat64Array`` ``double[]``
  398. ``PackedStringArray`` ``string[]``
  399. ``PackedColorArray`` ``Color[]``
  400. ``PackedVector2Array`` ``Vector2[]``
  401. ``PackedVector3Array`` ``Vector3[]``
  402. ====================== ==============================================================
  403. ``Godot.Collections.Array<T>`` is a type-safe wrapper around ``Godot.Collections.Array``.
  404. Use the ``Godot.Collections.Array<T>(Godot.Collections.Array)`` constructor to create one.
  405. Dictionary
  406. ----------
  407. Use ``Godot.Collections.Dictionary``.
  408. ``Godot.Collections.Dictionary<T>`` is a type-safe wrapper around ``Godot.Collections.Dictionary``.
  409. Use the ``Godot.Collections.Dictionary<T>(Godot.Collections.Dictionary)`` constructor to create one.
  410. List of Godot's Dictionary methods and their equivalent in C#:
  411. ======================= ==============================================================
  412. GDScript C#
  413. ======================= ==============================================================
  414. clear Clear
  415. duplicate Duplicate
  416. erase Remove
  417. find_key N/A
  418. get Dictionary[Variant] indexer or TryGetValue
  419. has ContainsKey
  420. has_all N/A
  421. hash GD.Hash
  422. is_empty Use ``Count == 0``
  423. is_read_only IsReadOnly
  424. keys Keys
  425. make_read_only MakeReadOnly
  426. merge Merge
  427. size Count
  428. values Values
  429. operator != !RecursiveEqual
  430. operator == RecursiveEqual
  431. operator [] Dictionary[Variant] indexer, Add or TryGetValue
  432. ======================= ==============================================================
  433. Variant
  434. -------
  435. ``Godot.Variant`` is used to represent the Godot's native :ref:`Variant <doc_variant_class>` type. Any Variant-compatible type can be converted from/to it.
  436. We recommend avoiding ``Godot.Variant`` unless it is necessary to interact with untyped engine APIs.
  437. Take advantage of C#'s type safety when possible.
  438. Any of ``Variant.As{TYPE}`` methods or the generic ``Variant.As<T>`` method can be used to convert
  439. a ``Godot.Variant`` to a C# type. Since the ``Godot.Variant`` type contains implicit conversions
  440. defined for all the supported types calling these methods directly is usually not necessary.
  441. Use ``CreateFrom`` method overloads or the generic ``From<T>`` method to convert a C# type
  442. to a ``Godot.Variant``.
  443. Communicating with other scripting languages
  444. --------------------------------------------
  445. This is explained extensively in :ref:`doc_cross_language_scripting`.
  446. .. _doc_c_sharp_differences_await:
  447. ``await`` keyword
  448. -----------------
  449. Something similar to GDScript's ``await`` keyword can be achieved with C#'s
  450. `await keyword <https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/await>`_.
  451. The ``await`` keyword in C# can be used with any awaitable expression. It's commonly
  452. used with operands of the types `Task`_, `Task<TResult>`_, `ValueTask`_, or `ValueTask<TResult>`_.
  453. An expression ``t`` is awaitable if one of the following holds:
  454. * ``t`` is of compile-time type ``dynamic``.
  455. * ``t`` has an accessible instance or extension method called ``GetAwaiter`` with no
  456. parameters and no type parameters, and a return type ``A`` for which all of the
  457. following hold:
  458. * ``A`` implements the interface ``System.Runtime.CompilerServices.INotifyCompletion``.
  459. * ``A`` has an accessible, readable instance property ``IsCompleted`` of type ``bool``.
  460. * ``A`` has an accessible instance method ``GetResult`` with no parameters and no type
  461. parameters.
  462. .. _Task: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task
  463. .. _Task<TResult>: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1
  464. .. _ValueTask: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask
  465. .. _ValueTask<TResult>: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask-1
  466. An equivalent of awaiting a signal in GDScript can be achieved with the ``await`` keyword and
  467. ``GodotObject.ToSignal``.
  468. Example:
  469. .. code-block:: csharp
  470. await ToSignal(timer, "timeout");
  471. GD.Print("After timeout");
  472. Other differences
  473. -----------------
  474. ``preload``, as it works in GDScript, is not available in C#.
  475. Use ``GD.Load`` or ``ResourceLoader.Load`` instead.
  476. Other differences:
  477. ================ ==================================================================
  478. GDScript C#
  479. ================ ==================================================================
  480. ``is_inf`` `float.IsInfinity`_ or `double.IsInfinity`_
  481. ``is_nan`` `float.IsNaN`_ or `double.IsNaN`_
  482. ``dict_to_inst`` TODO
  483. ``inst_to_dict`` TODO
  484. ================ ==================================================================
  485. .. _float.IsInfinity: https://learn.microsoft.com/en-us/dotnet/api/system.single.isinfinity
  486. .. _float.IsNaN: https://learn.microsoft.com/en-us/dotnet/api/system.single.isnan
  487. .. _double.IsInfinity: https://learn.microsoft.com/en-us/dotnet/api/system.double.isinfinity
  488. .. _double.IsNaN: https://learn.microsoft.com/en-us/dotnet/api/system.double.isnan