c_sharp_differences.rst 41 KB

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