c_sharp_differences.rst 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845
  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. ``instance_from_id(id)`` ``GodotObject.InstanceFromId(id)``
  56. ``is_instance_id_valid(id)`` ``GodotObject.IsInstanceIdValid(id)``
  57. ``is_instance_valid(obj)`` ``GodotObject.IsInstanceValid(obj)``
  58. ============================ =======================================================
  59. Tips
  60. ^^^^
  61. Sometimes it can be useful to use the ``using static`` directive. This directive allows
  62. to access the members and nested types of a class without specifying the class name.
  63. Example:
  64. .. code-block:: csharp
  65. using static Godot.GD;
  66. public class Test
  67. {
  68. static Test()
  69. {
  70. Print("Hello"); // Instead of GD.Print("Hello");
  71. }
  72. }
  73. Full list of equivalences
  74. ^^^^^^^^^^^^^^^^^^^^^^^^^
  75. List of Godot's global scope functions and their equivalent in C#:
  76. =============================== ==============================================================
  77. GDScript C#
  78. =============================== ==============================================================
  79. abs Mathf.Abs
  80. absf Mathf.Abs
  81. absi Mathf.Abs
  82. acos Mathf.Acos
  83. asin Mathf.Asin
  84. atan Mathf.Atan
  85. atan2 Mathf.Atan2
  86. bezier_derivative Mathf.BezierDerivative
  87. bezier_interpolate Mathf.BezierInterpolate
  88. bytes_to_var GD.BytesToVar
  89. bytes_to_var_with_objects GD.BytesToVarWithObjects
  90. ceil Mathf.Ceil
  91. ceilf Mathf.Ceil
  92. ceili Mathf.CeilToInt
  93. clamp Mathf.Clamp
  94. clampf Mathf.Clamp
  95. clampi Mathf.Clamp
  96. cos Mathf.Cos
  97. cosh Mathf.Cosh
  98. cubic_interpolate Mathf.CubicInterpolate
  99. cubic_interpoalte_angle Mathf.CubicInterpolateAngle
  100. cubic_interpolate_angle_in_time Mathf.CubicInterpolateInTime
  101. cubic_interpolate_in_time Mathf.CubicInterpolateAngleInTime
  102. db_to_linear Mathf.DbToLinear
  103. deg_to_rad Mathf.DegToRad
  104. ease Mathf.Ease
  105. error_string Error.ToString
  106. exp Mathf.Exp
  107. floor Mathf.Floor
  108. floorf Mathf.Floor
  109. floori Mathf.FloorToInt
  110. fmod operator %
  111. fposmod Mathf.PosMod
  112. hash GD.Hash
  113. instance_from_id GodotObject.InstanceFromId
  114. inverse_lerp Mathf.InverseLerp
  115. is_equal_approx Mathf.IsEqualApprox
  116. is_finite Mathf.IsFinite or `float.IsFinite`_ or `double.IsFinite`_
  117. is_inf Mathf.IsInf or `float.IsInfinity`_ or `double.IsInfinity`_
  118. is_instance_id_valid GodotObject.IsInstanceIdValid
  119. is_instance_valid GodotObject.IsInstanceValid
  120. is_nan Mathf.IsNaN or `float.IsNaN`_ or `double.IsNaN`_
  121. is_same operator == or `object.ReferenceEquals`_
  122. is_zero_approx Mathf.IsZeroApprox
  123. lerp Mathf.Lerp
  124. lerp_angle Mathf.LerpAngle
  125. lerpf Mathf.Lerp
  126. linear_to_db Mathf.LinearToDb
  127. log Mathf.Log
  128. max Mathf.Max
  129. maxf Mathf.Max
  130. maxi Mathf.Max
  131. min Mathf.Min
  132. minf Mathf.Min
  133. mini Mathf.Min
  134. move_toward Mathf.MoveToward
  135. nearest_po2 Mathf.NearestPo2
  136. pingpong Mathf.PingPong
  137. posmod Mathf.PosMod
  138. pow Mathf.Pow
  139. print GD.Print
  140. print_rich GD.PrintRich
  141. print_verbose Use OS.IsStdoutVerbose and GD.Print
  142. printerr GD.PrintErr
  143. printraw GD.PrintRaw
  144. prints GD.PrintS
  145. printt GD.PrintT
  146. push_error GD.PushError
  147. push_warning GD.PushWarning
  148. rad_to_deg Mathf.RadToDeg
  149. rand_from_seed GD.RandFromSeed
  150. randf GD.Randf
  151. randf_range GD.RandRange
  152. randfn GD.Randfn
  153. randi GD.Randi
  154. randi_range GD.RandRange
  155. randomize GD.Randomize
  156. remap Mathf.Remap
  157. rid_allocate_id N/A
  158. rid_from_int64 N/A
  159. round Mathf.Round
  160. roundf Mathf.Round
  161. roundi Mathf.RoundToInt
  162. seed GD.Seed
  163. sign Mathf.Sign
  164. signf Mathf.Sign
  165. signi Mathf.Sign
  166. sin Mathf.Sin
  167. sinh Mathf.Sinh
  168. smoothstep Mathf.SmoothStep
  169. snapped Mathf.Snapped
  170. snappedf Mathf.Snapped
  171. snappedi Mathf.Snapped
  172. sqrt Mathf.Sqrt
  173. step_decimals Mathf.StepDecimals
  174. str Use `$ string interpolation`_
  175. str_to_var GD.StrToVar
  176. tan Mathf.Tan
  177. tanh Mathf.Tanh
  178. typeof Variant.VariantType
  179. var_to_bytes GD.VarToBytes
  180. var_to_bytes_with_objects GD.VarToBytesWithObjects
  181. var_to_str GD.VarToStr
  182. weakref GodotObject.WeakRef
  183. wrap Mathf.Wrap
  184. wrapf Mathf.Wrap
  185. wrapi Mathf.Wrap
  186. =============================== ==============================================================
  187. .. _$ string interpolation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
  188. .. _double.IsFinite: https://learn.microsoft.com/en-us/dotnet/api/system.double.isfinite
  189. .. _double.IsInfinity: https://learn.microsoft.com/en-us/dotnet/api/system.double.isinfinity
  190. .. _double.IsNaN: https://learn.microsoft.com/en-us/dotnet/api/system.double.isnan
  191. .. _float.IsFinite: https://learn.microsoft.com/en-us/dotnet/api/system.single.isfinite
  192. .. _float.IsInfinity: https://learn.microsoft.com/en-us/dotnet/api/system.single.isinfinity
  193. .. _float.IsNaN: https://learn.microsoft.com/en-us/dotnet/api/system.single.isnan
  194. .. _object.ReferenceEquals: https://learn.microsoft.com/en-us/dotnet/api/system.object.referenceequals
  195. List of GDScript utility functions and their equivalent in C#:
  196. ======================= ==============================================================
  197. GDScript C#
  198. ======================= ==============================================================
  199. assert `System.Diagnostics.Debug.Assert`_
  200. char Use explicit conversion: ``(char)65``
  201. convert GD.Convert
  202. dict_to_inst N/A
  203. get_stack `System.Environment.StackTrace`_
  204. inst_to_dict N/A
  205. len N/A
  206. load GD.Load
  207. preload N/A
  208. print_debug N/A
  209. print_stack GD.Print(`System.Environment.StackTrace`_)
  210. range GD.Range or `System.Linq.Enumerable.Range`_
  211. type_exists ClassDB.ClassExists(type)
  212. ======================= ==============================================================
  213. .. _System.Diagnostics.Debug.Assert: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.debug.assert
  214. .. _System.Environment.StackTrace: https://learn.microsoft.com/en-us/dotnet/api/system.environment.stacktrace
  215. .. _System.Linq.Enumerable.Range: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.range
  216. ``preload``, as it works in GDScript, is not available in C#.
  217. Use ``GD.Load`` or ``ResourceLoader.Load`` instead.
  218. ``@export`` annotation
  219. ----------------------
  220. Use the ``[Export]`` attribute instead of the GDScript ``@export`` annotation.
  221. This attribute can also be provided with optional :ref:`PropertyHint<enum_@GlobalScope_PropertyHint>` and ``hintString`` parameters.
  222. Default values can be set by assigning a value.
  223. Example:
  224. .. code-block:: csharp
  225. using Godot;
  226. public partial class MyNode : Node
  227. {
  228. [Export]
  229. private NodePath _nodePath;
  230. [Export]
  231. private string _name = "default";
  232. [Export(PropertyHint.Range, "0,100000,1000,or_greater")]
  233. private int _income;
  234. [Export(PropertyHint.File, "*.png,*.jpg")]
  235. private string _icon;
  236. }
  237. See also: :ref:`doc_c_sharp_exports`.
  238. ``signal`` keyword
  239. ------------------
  240. Use the ``[Signal]`` attribute to declare a signal instead of the GDScript ``signal`` keyword.
  241. This attribute should be used on a `delegate`, whose name signature will be used to define the signal.
  242. 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``.
  243. .. code-block:: csharp
  244. [Signal]
  245. delegate void MySignalEventHandler(string willSendAString);
  246. See also: :ref:`doc_c_sharp_signals`.
  247. `@onready` annotation
  248. ---------------------
  249. GDScript has the ability to defer the initialization of a member variable until the ready function
  250. is called with `@onready` (cf. :ref:`doc_gdscript_onready_annotation`).
  251. For example:
  252. .. code-block:: gdscript
  253. @onready var my_label = get_node("MyLabel")
  254. However C# does not have this ability. To achieve the same effect you need to do this.
  255. .. code-block:: csharp
  256. private Label _myLabel;
  257. public override void _Ready()
  258. {
  259. _myLabel = GetNode<Label>("MyLabel");
  260. }
  261. Singletons
  262. ----------
  263. Singletons are available as static classes rather than using the singleton pattern.
  264. This is to make code less verbose than it would be with an ``Instance`` property.
  265. Example:
  266. .. code-block:: csharp
  267. Input.IsActionPressed("ui_down")
  268. However, in some very rare cases this is not enough. For example, you may want
  269. to access a member from the base class ``GodotObject``, like ``Connect``.
  270. For such use cases we provide a static property named ``Singleton`` that returns
  271. the singleton instance. The type of this instance is ``GodotObject``.
  272. Example:
  273. .. code-block:: csharp
  274. Input.Singleton.JoyConnectionChanged += Input_JoyConnectionChanged;
  275. String
  276. ------
  277. Use ``System.String`` (``string``). Most of Godot's String methods have an
  278. equivalent in ``System.String`` or are provided by the ``StringExtensions``
  279. class as extension methods.
  280. Example:
  281. .. code-block:: csharp
  282. string text = "Get up!";
  283. string[] bigrams = text.Bigrams(); // ["Ge", "et", "t ", " u", "up", "p!"]
  284. Strings are immutable in .NET, so all methods that manipulate a string don't
  285. modify the original string and return a newly created string with the
  286. modifications applied. To avoid creating multiple string allocations consider
  287. using a `StringBuilder`_.
  288. List of Godot's String methods and their equivalent in C#:
  289. ======================= ==============================================================
  290. GDScript C#
  291. ======================= ==============================================================
  292. begins_with `string.StartsWith`_
  293. bigrams StringExtensions.Bigrams
  294. bin_to_int StringExtensions.BinToInt
  295. c_escape StringExtensions.CEscape
  296. c_unescape StringExtensions.CUnescape
  297. capitalize StringExtensions.Capitalize
  298. casecmp_to StringExtensions.CasecmpTo or StringExtensions.CompareTo (Consider using `string.Equals`_ or `string.Compare`_)
  299. chr N/A
  300. contains `string.Contains`_
  301. count StringExtensions.Count (Consider using `RegEx`_)
  302. countn StringExtensions.CountN (Consider using `RegEx`_)
  303. dedent StringExtensions.Dedent
  304. ends_with `string.EndsWith`_
  305. find StringExtensions.Find (Consider using `string.IndexOf`_ or `string.IndexOfAny`_)
  306. findn StringExtensions.FindN (Consider using `string.IndexOf`_ or `string.IndexOfAny`_)
  307. format Use `$ string interpolation`_
  308. get_base_dir StringExtensions.GetBaseDir
  309. get_basename StringExtensions.GetBaseName
  310. get_extension StringExtensions.GetExtension
  311. get_file StringExtensions.GetFile
  312. get_slice N/A
  313. get_slice_count N/A
  314. get_slicec N/A
  315. hash StringExtensions.Hash (Consider using `object.GetHashCode`_ unless you need to guarantee the same behavior as in GDScript)
  316. hex_to_int StringExtensions.HexToInt (Consider using `int.Parse`_ or `long.Parse`_ with `System.Globalization.NumberStyles.HexNumber`_)
  317. humanize_size N/A
  318. indent StringExtensions.Indent
  319. insert `string.Insert`_ (Consider using `StringBuilder`_ to manipulate strings)
  320. is_absolute_path StringExtensions.IsAbsolutePath
  321. is_empty `string.IsNullOrEmpty`_ or `string.IsNullOrWhiteSpace`_
  322. is_relative_path StringExtensions.IsRelativePath
  323. is_subsequence_of StringExtensions.IsSubsequenceOf
  324. is_subsequence_ofn StringExtensions.IsSubsequenceOfN
  325. is_valid_filename StringExtensions.IsValidFileName
  326. is_valid_float StringExtensions.IsValidFloat (Consider using `float.TryParse`_ or `double.TryParse`_)
  327. is_valid_hex_number StringExtensions.IsValidHexNumber
  328. is_valid_html_color StringExtensions.IsValidHtmlColor
  329. is_valid_identifier StringExtensions.IsValidIdentifier
  330. is_valid_int StringExtensions.IsValidInt (Consider using `int.TryParse`_ or `long.TryParse`_)
  331. is_valid_ip_address StringExtensions.IsValidIPAddress
  332. join `string.Join`_
  333. json_escape StringExtensions.JSONEscape
  334. left StringExtensions.Left (Consider using `string.Substring`_ or `string.AsSpan`_)
  335. length `string.Length`_
  336. lpad `string.PadLeft`_
  337. lstrip `string.TrimStart`_
  338. match StringExtensions.Match (Consider using `RegEx`_)
  339. matchn StringExtensions.MatchN (Consider using `RegEx`_)
  340. md5_buffer StringExtensions.Md5Buffer (Consider using `System.Security.Cryptography.MD5.HashData`_)
  341. md5_text StringExtensions.Md5Text (Consider using `System.Security.Cryptography.MD5.HashData`_ with StringExtensions.HexEncode)
  342. naturalnocasecmp_to N/A (Consider using `string.Equals`_ or `string.Compare`_)
  343. nocasecmp_to StringExtensions.NocasecmpTo or StringExtensions.CompareTo (Consider using `string.Equals`_ or `string.Compare`_)
  344. num `float.ToString`_ or `double.ToString`_
  345. num_int64 `int.ToString`_ or `long.ToString`_
  346. num_scientific `float.ToString`_ or `double.ToString`_
  347. num_uint64 `uint.ToString`_ or `ulong.ToString`_
  348. pad_decimals StringExtensions.PadDecimals
  349. pad_zeros StringExtensions.PadZeros
  350. path_join StringExtensions.PathJoin
  351. repeat Use `string constructor`_ or a `StringBuilder`_
  352. replace `string.Replace`_ or `RegEx`_
  353. replacen StringExtensions.ReplaceN (Consider using `string.Replace`_ or `RegEx`_)
  354. rfind StringExtensions.RFind (Consider using `string.LastIndexOf`_ or `string.LastIndexOfAny`_)
  355. rfindn StringExtensions.RFindN (Consider using `string.LastIndexOf`_ or `string.LastIndexOfAny`_)
  356. right StringExtensions.Right (Consider using `string.Substring`_ or `string.AsSpan`_)
  357. rpad `string.PadRight`_
  358. rsplit N/A
  359. rstrip `string.TrimEnd`_
  360. sha1_buffer StringExtensions.Sha1Buffer (Consider using `System.Security.Cryptography.SHA1.HashData`_)
  361. sha1_text StringExtensions.Sha1Text (Consider using `System.Security.Cryptography.SHA1.HashData`_ with StringExtensions.HexEncode)
  362. sha256_buffer StringExtensions.Sha256Buffer (Consider using `System.Security.Cryptography.SHA256.HashData`_)
  363. sha256_text StringExtensions.Sha256Text (Consider using `System.Security.Cryptography.SHA256.HashData`_ with StringExtensions.HexEncode)
  364. similarity StringExtensions.Similarity
  365. simplify_path StringExtensions.SimplifyPath
  366. split StringExtensions.Split (Consider using `string.Split`_)
  367. split_floats StringExtensions.SplitFloat
  368. strip_edges StringExtensions.StripEdges (Consider using `string.Trim`_, `string.TrimStart`_ or `string.TrimEnd`_)
  369. strip_escapes StringExtensions.StripEscapes
  370. substr StringExtensions.Substr (Consider using `string.Substring`_ or `string.AsSpan`_)
  371. to_ascii_buffer StringExtensions.ToAsciiBuffer (Consider using `System.Text.Encoding.ASCII.GetBytes`_)
  372. to_camel_case StringExtensions.ToCamelCase
  373. to_float StringExtensions.ToFloat (Consider using `float.TryParse`_ or `double.TryParse`_)
  374. to_int StringExtensions.ToInt (Consider using `int.TryParse`_ or `long.TryParse`_)
  375. to_lower `string.ToLower`_
  376. to_pascal_case StringExtensions.ToPascalCase
  377. to_snake_case StringExtensions.ToSnakeCase
  378. to_upper `string.ToUpper`_
  379. to_utf16_buffer StringExtensions.ToUtf16Buffer (Consider using `System.Text.Encoding.UTF16.GetBytes`_)
  380. to_utf32_buffer StringExtensions.ToUtf32Buffer (Consider using `System.Text.Encoding.UTF32.GetBytes`_)
  381. to_utf8_buffer StringExtensions.ToUtf8Buffer (Consider using `System.Text.Encoding.UTF8.GetBytes`_)
  382. trim_prefix StringExtensions.TrimPrefix
  383. trim_suffix StringExtensions.TrimSuffix
  384. unicode_at `string[int]`_ indexer
  385. uri_decode StringExtensions.URIDecode (Consider using `System.Uri.UnescapeDataString`_)
  386. uri_encode StringExtensions.URIEncode (Consider using `System.Uri.EscapeDataString`_)
  387. validate_node_name StringExtensions.ValidateNodeName
  388. xml_escape StringExtensions.XMLEscape
  389. xml_unescape StringExtensions.XMLUnescape
  390. ======================= ==============================================================
  391. List of Godot's PackedByteArray methods that create a String and their C# equivalent:
  392. ========================= ==============================================================
  393. GDScript C#
  394. ========================= ==============================================================
  395. get_string_from_ascii StringExtensions.GetStringFromAscii (Consider using `System.Text.Encoding.ASCII.GetString`_)
  396. get_string_from_utf16 StringExtensions.GetStringFromUtf16 (Consider using `System.Text.Encoding.UTF16.GetString`_)
  397. get_string_from_utf32 StringExtensions.GetStringFromUtf32 (Consider using `System.Text.Encoding.UTF32.GetString`_)
  398. get_string_from_utf8 StringExtensions.GetStringFromUtf8 (Consider using `System.Text.Encoding.UTF8.GetString`_)
  399. hex_encode StringExtensions.HexEncode (Consider using `System.Convert.ToHexString`_)
  400. ========================= ==============================================================
  401. * .NET contains many path utility methods available under the
  402. `System.IO.Path`_
  403. class that can be used when not dealing with Godot paths (paths that start
  404. with ``res://`` or ``user://``)
  405. .. _$ string interpolation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
  406. .. _double.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.double.tostring
  407. .. _double.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse
  408. .. _float.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.single.tostring
  409. .. _float.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.single.tryparse
  410. .. _int.Parse: https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse
  411. .. _int.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tostring
  412. .. _int.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse
  413. .. _long.Parse: https://learn.microsoft.com/en-us/dotnet/api/system.int64.parse
  414. .. _long.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tostring
  415. .. _long.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse
  416. .. _uint.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tostring
  417. .. _ulong.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tostring
  418. .. _object.GetHashCode: https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode
  419. .. _RegEx: https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expressions
  420. .. _string constructor: https://learn.microsoft.com/en-us/dotnet/api/system.string.-ctor
  421. .. _string[int]: https://learn.microsoft.com/en-us/dotnet/api/system.string.chars
  422. .. _string.AsSpan: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.asspan
  423. .. _string.Compare: https://learn.microsoft.com/en-us/dotnet/api/system.string.compare
  424. .. _string.Contains: https://learn.microsoft.com/en-us/dotnet/api/system.string.contains
  425. .. _string.EndsWith: https://learn.microsoft.com/en-us/dotnet/api/system.string.endswith
  426. .. _string.Equals: https://learn.microsoft.com/en-us/dotnet/api/system.string.equals
  427. .. _string.IndexOf: https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof
  428. .. _string.IndexOfAny: https://learn.microsoft.com/en-us/dotnet/api/system.string.indexofany
  429. .. _string.Insert: https://learn.microsoft.com/en-us/dotnet/api/system.string.insert
  430. .. _string.IsNullOrEmpty: https://learn.microsoft.com/en-us/dotnet/api/system.string.isnullorempty
  431. .. _string.IsNullOrWhiteSpace: https://learn.microsoft.com/en-us/dotnet/api/system.string.isnullorwhitespace
  432. .. _string.Join: https://learn.microsoft.com/en-us/dotnet/api/system.string.join
  433. .. _string.LastIndexOf: https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexof
  434. .. _string.LastIndexOfAny: https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexofany
  435. .. _string.Length: https://learn.microsoft.com/en-us/dotnet/api/system.string.length
  436. .. _string.PadLeft: https://learn.microsoft.com/en-us/dotnet/api/system.string.padleft
  437. .. _string.PadRight: https://learn.microsoft.com/en-us/dotnet/api/system.string.padright
  438. .. _string.Replace: https://learn.microsoft.com/en-us/dotnet/api/system.string.replace
  439. .. _string.Split: https://learn.microsoft.com/en-us/dotnet/api/system.string.split
  440. .. _string.StartsWith: https://learn.microsoft.com/en-us/dotnet/api/system.string.startswith
  441. .. _string.Substring: https://learn.microsoft.com/en-us/dotnet/api/system.string.substring
  442. .. _string.Trim: https://learn.microsoft.com/en-us/dotnet/api/system.string.trim
  443. .. _string.TrimEnd: https://learn.microsoft.com/en-us/dotnet/api/system.string.trimend
  444. .. _string.TrimStart: https://learn.microsoft.com/en-us/dotnet/api/system.string.trimstart
  445. .. _string.ToLower: https://learn.microsoft.com/en-us/dotnet/api/system.string.tolower
  446. .. _string.ToUpper: https://learn.microsoft.com/en-us/dotnet/api/system.string.toupper
  447. .. _StringBuilder: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder
  448. .. _System.Convert.ToHexString: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring
  449. .. _System.Globalization.NumberStyles.HexNumber: https://learn.microsoft.com/en-us/dotnet/api/system.globalization.numberstyles#system-globalization-numberstyles-hexnumber
  450. .. _System.IO.Path: https://learn.microsoft.com/en-us/dotnet/api/system.io.path
  451. .. _System.Security.Cryptography.MD5.HashData: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5.hashdata
  452. .. _System.Security.Cryptography.SHA1.HashData: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha1.hashdata
  453. .. _System.Security.Cryptography.SHA256.HashData: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata
  454. .. _System.Text.Encoding.ASCII.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.asciiencoding.getbytes
  455. .. _System.Text.Encoding.ASCII.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.asciiencoding.getstring
  456. .. _System.Text.Encoding.UTF16.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.unicodeencoding.getbytes
  457. .. _System.Text.Encoding.UTF16.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.unicodeencoding.getstring
  458. .. _System.Text.Encoding.UTF32.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf32encoding.getbytes
  459. .. _System.Text.Encoding.UTF32.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf32encoding.getstring
  460. .. _System.Text.Encoding.UTF8.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf8encoding.getbytes
  461. .. _System.Text.Encoding.UTF8.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf8encoding.getstring
  462. .. _System.Uri.EscapeDataString: https://learn.microsoft.com/en-us/dotnet/api/system.uri.escapedatastring
  463. .. _System.Uri.UnescapeDataString: https://learn.microsoft.com/en-us/dotnet/api/system.uri.unescapedatastring
  464. NodePath
  465. --------
  466. The following method was converted to a property with a different name:
  467. ==================== ==============================================================
  468. GDScript C#
  469. ==================== ==============================================================
  470. ``is_empty()`` ``IsEmpty``
  471. ==================== ==============================================================
  472. Signal
  473. ------
  474. The following methods were converted to properties with their respective names changed:
  475. ==================== ==============================================================
  476. GDScript C#
  477. ==================== ==============================================================
  478. ``get_name()`` ``Name``
  479. ``get_object()`` ``Owner``
  480. ==================== ==============================================================
  481. The ``Signal`` type implements the awaitable pattern which means it can be used with
  482. the ``await`` keyword. See :ref:`doc_c_sharp_differences_await`.
  483. Instead of using the ``Signal`` type, the recommended way to use Godot signals in C# is
  484. to use the generated C# events. See :ref:`doc_c_sharp_signals`.
  485. Callable
  486. --------
  487. The following methods were converted to properties with their respective names changed:
  488. ==================== ==============================================================
  489. GDScript C#
  490. ==================== ==============================================================
  491. ``get_object()`` ``Target``
  492. ``get_method()`` ``Method``
  493. ==================== ==============================================================
  494. Currently C# supports ``Callable`` if one of the following holds:
  495. * ``Callable`` was created using the C# ``Callable`` type.
  496. * ``Callable`` is a basic version of the engine's ``Callable``. Custom ``Callable``\ s
  497. are unsupported. A ``Callable`` is custom when any of the following holds:
  498. * ``Callable`` has bound information (``Callable``\ s created with ``bind``/``unbind`` are unsupported).
  499. * ``Callable`` was created from other languages through the GDExtension API.
  500. Some methods such as ``bind`` and ``unbind`` are not implemented, use lambdas instead:
  501. .. code-block:: csharp
  502. string name = "John Doe";
  503. Callable callable = Callable.From(() => SayHello(name));
  504. void SayHello(string name)
  505. {
  506. GD.Print($"Hello {name}");
  507. }
  508. The lambda captures the ``name`` variable so it can be bound to the ``SayHello`` method.
  509. RID
  510. ---
  511. This type is named ``Rid`` in C# to follow the .NET naming convention.
  512. The following methods were converted to properties with their respective names changed:
  513. ==================== ==============================================================
  514. GDScript C#
  515. ==================== ==============================================================
  516. ``get_id()`` ``Id``
  517. ``is_valid()`` ``IsValid``
  518. ==================== ==============================================================
  519. Basis
  520. -----
  521. Structs cannot have parameterless constructors in C#. Therefore, ``new Basis()``
  522. initializes all primitive members to their default value. Use ``Basis.Identity``
  523. for the equivalent of ``Basis()`` in GDScript and C++.
  524. The following method was converted to a property with a different name:
  525. ==================== ==============================================================
  526. GDScript C#
  527. ==================== ==============================================================
  528. ``get_scale()`` ``Scale``
  529. ==================== ==============================================================
  530. Transform2D
  531. -----------
  532. Structs cannot have parameterless constructors in C#. Therefore, ``new Transform2D()``
  533. initializes all primitive members to their default value.
  534. Please use ``Transform2D.Identity`` for the equivalent of ``Transform2D()`` in GDScript and C++.
  535. The following methods were converted to properties with their respective names changed:
  536. ==================== ==============================================================
  537. GDScript C#
  538. ==================== ==============================================================
  539. ``get_rotation()`` ``Rotation``
  540. ``get_scale()`` ``Scale``
  541. ``get_skew()`` ``Skew``
  542. ==================== ==============================================================
  543. Transform3D
  544. -----------
  545. Structs cannot have parameterless constructors in C#. Therefore, ``new Transform3D()``
  546. initializes all primitive members to their default value.
  547. Please use ``Transform3D.Identity`` for the equivalent of ``Transform3D()`` in GDScript and C++.
  548. The following methods were converted to properties with their respective names changed:
  549. ==================== ==============================================================
  550. GDScript C#
  551. ==================== ==============================================================
  552. ``get_rotation()`` ``Rotation``
  553. ``get_scale()`` ``Scale``
  554. ==================== ==============================================================
  555. Rect2
  556. -----
  557. The following field was converted to a property with a *slightly* different name:
  558. ================ ==================================================================
  559. GDScript C#
  560. ================ ==================================================================
  561. ``end`` ``End``
  562. ================ ==================================================================
  563. The following method was converted to a property with a different name:
  564. ================ ==================================================================
  565. GDScript C#
  566. ================ ==================================================================
  567. ``get_area()`` ``Area``
  568. ================ ==================================================================
  569. Rect2i
  570. ------
  571. This type is named ``Rect2I`` in C# to follow the .NET naming convention.
  572. The following field was converted to a property with a *slightly* different name:
  573. ================ ==================================================================
  574. GDScript C#
  575. ================ ==================================================================
  576. ``end`` ``End``
  577. ================ ==================================================================
  578. The following method was converted to a property with a different name:
  579. ================ ==================================================================
  580. GDScript C#
  581. ================ ==================================================================
  582. ``get_area()`` ``Area``
  583. ================ ==================================================================
  584. AABB
  585. ----
  586. This type is named ``Aabb`` in C# to follow the .NET naming convention.
  587. The following method was converted to a property with a different name:
  588. ================ ==================================================================
  589. GDScript C#
  590. ================ ==================================================================
  591. ``get_volume()`` ``Volume``
  592. ================ ==================================================================
  593. Quaternion
  594. ----------
  595. Structs cannot have parameterless constructors in C#. Therefore, ``new Quaternion()``
  596. initializes all primitive members to their default value.
  597. Please use ``Quaternion.Identity`` for the equivalent of ``Quaternion()`` in GDScript and C++.
  598. Projection
  599. ----------
  600. Structs cannot have parameterless constructors in C#. Therefore, ``new Projection()``
  601. initializes all primitive members to their default value.
  602. Please use ``Projection.Identity`` for the equivalent of ``Projection()`` in GDScript and C++.
  603. Color
  604. -----
  605. Structs cannot have parameterless constructors in C#. Therefore, ``new Color()``
  606. initializes all primitive members to their default value (which represents the transparent black color).
  607. Please use ``Colors.Black`` for the equivalent of ``Color()`` in GDScript and C++.
  608. The global ``Color8`` method to construct a Color from bytes is available as a static method
  609. in the Color type.
  610. The Color constants are available in the ``Colors`` static class as readonly properties.
  611. The following method was converted to a property with a different name:
  612. ==================== ==============================================================
  613. GDScript C#
  614. ==================== ==============================================================
  615. ``get_luminance()`` ``Luminance``
  616. ==================== ==============================================================
  617. The following method was converted to a method with a different name:
  618. ==================== ==============================================================
  619. GDScript C#
  620. ==================== ==============================================================
  621. ``html(String)`` ``FromHtml(ReadOnlySpan<char>)``
  622. ==================== ==============================================================
  623. The following methods are available as constructors:
  624. ==================== ==============================================================
  625. GDScript C#
  626. ==================== ==============================================================
  627. ``hex(int)`` ``Color(uint)``
  628. ``hex64(int)`` ``Color(ulong)``
  629. ==================== ==============================================================
  630. Array
  631. -----
  632. The equivalent of packed arrays are ``System.Array``.
  633. See also :ref:`PackedArray in C# <doc_c_sharp_collections_packedarray>`.
  634. Use ``Godot.Collections.Array`` for an untyped ``Variant`` array.
  635. ``Godot.Collections.Array<T>`` is a type-safe wrapper around ``Godot.Collections.Array``.
  636. See also :ref:`Array in C# <doc_c_sharp_collections_array>`.
  637. Dictionary
  638. ----------
  639. Use ``Godot.Collections.Dictionary`` for an untyped ``Variant`` dictionary.
  640. ``Godot.Colelctions.Dictionary<TKey, TValue>`` is a type-safe wrapper around ``Godot.Collections.Dictionary``.
  641. See also :ref:`Dictionary in C# <doc_c_sharp_collections_dictionary>`.
  642. Variant
  643. -------
  644. ``Godot.Variant`` is used to represent Godot's native :ref:`Variant <class_Variant>` type.
  645. Any Variant-compatible type can be converted from/to it.
  646. See also: :ref:`doc_c_sharp_variant`.
  647. Communicating with other scripting languages
  648. --------------------------------------------
  649. This is explained extensively in :ref:`doc_cross_language_scripting`.
  650. .. _doc_c_sharp_differences_await:
  651. ``await`` keyword
  652. -----------------
  653. Something similar to GDScript's ``await`` keyword can be achieved with C#'s
  654. `await keyword <https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/await>`_.
  655. The ``await`` keyword in C# can be used with any awaitable expression. It's commonly
  656. used with operands of the types `Task`_, `Task<TResult>`_, `ValueTask`_, or `ValueTask<TResult>`_.
  657. An expression ``t`` is awaitable if one of the following holds:
  658. * ``t`` is of compile-time type ``dynamic``.
  659. * ``t`` has an accessible instance or extension method called ``GetAwaiter`` with no
  660. parameters and no type parameters, and a return type ``A`` for which all of the
  661. following hold:
  662. * ``A`` implements the interface ``System.Runtime.CompilerServices.INotifyCompletion``.
  663. * ``A`` has an accessible, readable instance property ``IsCompleted`` of type ``bool``.
  664. * ``A`` has an accessible instance method ``GetResult`` with no parameters and no type
  665. parameters.
  666. .. _Task: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task
  667. .. _Task<TResult>: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1
  668. .. _ValueTask: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask
  669. .. _ValueTask<TResult>: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask-1
  670. An equivalent of awaiting a signal in GDScript can be achieved with the ``await`` keyword and
  671. ``GodotObject.ToSignal``.
  672. Example:
  673. .. code-block:: csharp
  674. await ToSignal(timer, "timeout");
  675. GD.Print("After timeout");