c_sharp_differences.rst 42 KB

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