c_sharp_differences.rst 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  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. Example:
  309. .. code-block:: csharp
  310. string text = "Get up!";
  311. string[] bigrams = text.Bigrams(); // ["Ge", "et", "t ", " u", "up", "p!"]
  312. Strings are immutable in .NET, so all methods that manipulate a string don't
  313. modify the original string and return a newly created string with the
  314. modifications applied. To avoid creating multiple string allocations consider
  315. using a `StringBuilder`_.
  316. List of Godot's String methods and their equivalent in C#:
  317. ======================= ==============================================================
  318. GDScript C#
  319. ======================= ==============================================================
  320. begins_with `string.StartsWith`_
  321. bigrams StringExtensions.Bigrams
  322. bin_to_int StringExtensions.BinToInt
  323. c_escape StringExtensions.CEscape
  324. c_unescape StringExtensions.CUnescape
  325. capitalize StringExtensions.Capitalize
  326. casecmp_to StringExtensions.CasecmpTo or StringExtensions.CompareTo (Consider using `string.Equals`_ or `string.Compare`_)
  327. chr N/A
  328. contains `string.Contains`_
  329. count StringExtensions.Count (Consider using `RegEx`_)
  330. countn StringExtensions.CountN (Consider using `RegEx`_)
  331. dedent StringExtensions.Dedent
  332. ends_with `string.EndsWith`_
  333. erase `string.Remove`_ (Consider using `StringBuilder`_ to manipulate strings)
  334. find StringExtensions.Find (Consider using `string.IndexOf`_ or `string.IndexOfAny`_)
  335. findn StringExtensions.FindN (Consider using `string.IndexOf`_ or `string.IndexOfAny`_)
  336. format Use `$ string interpolation`_
  337. get_base_dir StringExtensions.GetBaseDir
  338. get_basename StringExtensions.GetBaseName
  339. get_extension StringExtensions.GetExtension
  340. get_file StringExtensions.GetFile
  341. get_slice N/A
  342. get_slice_count N/A
  343. get_slicec N/A
  344. hash StringExtensions.Hash (Consider using `object.GetHashCode`_ unless you need to guarantee the same behavior as in GDScript)
  345. hex_decode StringExtensions.HexDecode (Consider using `System.Convert.FromHexString`_)
  346. hex_to_int StringExtensions.HexToInt (Consider using `int.Parse`_ or `long.Parse`_ with `System.Globalization.NumberStyles.HexNumber`_)
  347. humanize_size N/A
  348. indent StringExtensions.Indent
  349. insert `string.Insert`_ (Consider using `StringBuilder`_ to manipulate strings)
  350. is_absolute_path StringExtensions.IsAbsolutePath
  351. is_empty `string.IsNullOrEmpty`_ or `string.IsNullOrWhiteSpace`_
  352. is_relative_path StringExtensions.IsRelativePath
  353. is_subsequence_of StringExtensions.IsSubsequenceOf
  354. is_subsequence_ofn StringExtensions.IsSubsequenceOfN
  355. is_valid_filename StringExtensions.IsValidFileName
  356. is_valid_float StringExtensions.IsValidFloat (Consider using `float.TryParse`_ or `double.TryParse`_)
  357. is_valid_hex_number StringExtensions.IsValidHexNumber
  358. is_valid_html_color StringExtensions.IsValidHtmlColor
  359. is_valid_identifier StringExtensions.IsValidIdentifier
  360. is_valid_int StringExtensions.IsValidInt (Consider using `int.TryParse`_ or `long.TryParse`_)
  361. is_valid_ip_address StringExtensions.IsValidIPAddress
  362. join `string.Join`_
  363. json_escape StringExtensions.JSONEscape
  364. left StringExtensions.Left (Consider using `string.Substring`_ or `string.AsSpan`_)
  365. length `string.Length`_
  366. lpad `string.PadLeft`_
  367. lstrip `string.TrimStart`_
  368. match StringExtensions.Match (Consider using `RegEx`_)
  369. matchn StringExtensions.MatchN (Consider using `RegEx`_)
  370. md5_buffer StringExtensions.Md5Buffer (Consider using `System.Security.Cryptography.MD5.HashData`_)
  371. md5_text StringExtensions.Md5Text (Consider using `System.Security.Cryptography.MD5.HashData`_ with StringExtensions.HexEncode)
  372. naturalnocasecmp_to N/A (Consider using `string.Equals`_ or `string.Compare`_)
  373. nocasecmp_to StringExtensions.NocasecmpTo or StringExtensions.CompareTo (Consider using `string.Equals`_ or `string.Compare`_)
  374. num `float.ToString`_ or `double.ToString`_
  375. num_int64 `int.ToString`_ or `long.ToString`_
  376. num_scientific `float.ToString`_ or `double.ToString`_
  377. num_uint64 `uint.ToString`_ or `ulong.ToString`_
  378. pad_decimals StringExtensions.PadDecimals
  379. pad_zeros StringExtensions.PadZeros
  380. path_join StringExtensions.PathJoin
  381. repeat Use `string constructor`_ or a `StringBuilder`_
  382. replace `string.Replace`_ or `RegEx`_
  383. replacen StringExtensions.ReplaceN (Consider using `string.Replace`_ or `RegEx`_)
  384. reverse N/A
  385. rfind StringExtensions.RFind (Consider using `string.LastIndexOf`_ or `string.LastIndexOfAny`_)
  386. rfindn StringExtensions.RFindN (Consider using `string.LastIndexOf`_ or `string.LastIndexOfAny`_)
  387. right StringExtensions.Right (Consider using `string.Substring`_ or `string.AsSpan`_)
  388. rpad `string.PadRight`_
  389. rsplit N/A
  390. rstrip `string.TrimEnd`_
  391. sha1_buffer StringExtensions.Sha1Buffer (Consider using `System.Security.Cryptography.SHA1.HashData`_)
  392. sha1_text StringExtensions.Sha1Text (Consider using `System.Security.Cryptography.SHA1.HashData`_ with StringExtensions.HexEncode)
  393. sha256_buffer StringExtensions.Sha256Buffer (Consider using `System.Security.Cryptography.SHA256.HashData`_)
  394. sha256_text StringExtensions.Sha256Text (Consider using `System.Security.Cryptography.SHA256.HashData`_ with StringExtensions.HexEncode)
  395. similarity StringExtensions.Similarity
  396. simplify_path StringExtensions.SimplifyPath
  397. split StringExtensions.Split (Consider using `string.Split`_)
  398. split_floats StringExtensions.SplitFloat
  399. strip_edges StringExtensions.StripEdges (Consider using `string.Trim`_, `string.TrimStart`_ or `string.TrimEnd`_)
  400. strip_escapes StringExtensions.StripEscapes
  401. substr StringExtensions.Substr (Consider using `string.Substring`_ or `string.AsSpan`_)
  402. to_ascii_buffer StringExtensions.ToAsciiBuffer (Consider using `System.Text.Encoding.ASCII.GetBytes`_)
  403. to_camel_case StringExtensions.ToCamelCase
  404. to_float StringExtensions.ToFloat (Consider using `float.TryParse`_ or `double.TryParse`_)
  405. to_int StringExtensions.ToInt (Consider using `int.TryParse`_ or `long.TryParse`_)
  406. to_lower `string.ToLower`_
  407. to_pascal_case StringExtensions.ToPascalCase
  408. to_snake_case StringExtensions.ToSnakeCase
  409. to_upper `string.ToUpper`_
  410. to_utf16_buffer StringExtensions.ToUtf16Buffer (Consider using `System.Text.Encoding.UTF16.GetBytes`_)
  411. to_utf32_buffer StringExtensions.ToUtf32Buffer (Consider using `System.Text.Encoding.UTF32.GetBytes`_)
  412. to_utf8_buffer StringExtensions.ToUtf8Buffer (Consider using `System.Text.Encoding.UTF8.GetBytes`_)
  413. to_wchar_buffer StringExtensions.ToUtf16Buffer in Windows and StringExtensions.ToUtf32Buffer in other platforms
  414. trim_prefix StringExtensions.TrimPrefix
  415. trim_suffix StringExtensions.TrimSuffix
  416. unicode_at `string[int]`_ indexer
  417. uri_decode StringExtensions.URIDecode (Consider using `System.Uri.UnescapeDataString`_)
  418. uri_encode StringExtensions.URIEncode (Consider using `System.Uri.EscapeDataString`_)
  419. validate_node_name StringExtensions.ValidateNodeName
  420. xml_escape StringExtensions.XMLEscape
  421. xml_unescape StringExtensions.XMLUnescape
  422. ======================= ==============================================================
  423. List of Godot's PackedByteArray methods that create a String and their C# equivalent:
  424. ========================= ==============================================================
  425. GDScript C#
  426. ========================= ==============================================================
  427. get_string_from_ascii StringExtensions.GetStringFromAscii (Consider using `System.Text.Encoding.ASCII.GetString`_)
  428. get_string_from_utf16 StringExtensions.GetStringFromUtf16 (Consider using `System.Text.Encoding.UTF16.GetString`_)
  429. get_string_from_utf32 StringExtensions.GetStringFromUtf32 (Consider using `System.Text.Encoding.UTF32.GetString`_)
  430. get_string_from_utf8 StringExtensions.GetStringFromUtf8 (Consider using `System.Text.Encoding.UTF8.GetString`_)
  431. hex_encode StringExtensions.HexEncode (Consider using `System.Convert.ToHexString`_)
  432. ========================= ==============================================================
  433. .. note::
  434. .NET provides path utility methods under the
  435. `System.IO.Path`_
  436. class. They can only be used with native OS paths, not Godot paths
  437. (paths that start with ``res://`` or ``user://``).
  438. See :ref:`doc_data_paths`.
  439. .. _$ string interpolation: https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/tokens/interpolated
  440. .. _double.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.double.tostring
  441. .. _double.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.double.tryparse
  442. .. _float.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.single.tostring
  443. .. _float.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.single.tryparse
  444. .. _int.Parse: https://learn.microsoft.com/en-us/dotnet/api/system.int32.parse
  445. .. _int.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tostring
  446. .. _int.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.int32.tryparse
  447. .. _long.Parse: https://learn.microsoft.com/en-us/dotnet/api/system.int64.parse
  448. .. _long.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tostring
  449. .. _long.TryParse: https://learn.microsoft.com/en-us/dotnet/api/system.int64.tryparse
  450. .. _uint.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.uint32.tostring
  451. .. _ulong.ToString: https://learn.microsoft.com/en-us/dotnet/api/system.uint64.tostring
  452. .. _object.GetHashCode: https://learn.microsoft.com/en-us/dotnet/api/system.object.gethashcode
  453. .. _RegEx: https://learn.microsoft.com/en-us/dotnet/standard/base-types/regular-expressions
  454. .. _string constructor: https://learn.microsoft.com/en-us/dotnet/api/system.string.-ctor
  455. .. _string[int]: https://learn.microsoft.com/en-us/dotnet/api/system.string.chars
  456. .. _string.AsSpan: https://learn.microsoft.com/en-us/dotnet/api/system.memoryextensions.asspan
  457. .. _string.Compare: https://learn.microsoft.com/en-us/dotnet/api/system.string.compare
  458. .. _string.Contains: https://learn.microsoft.com/en-us/dotnet/api/system.string.contains
  459. .. _string.EndsWith: https://learn.microsoft.com/en-us/dotnet/api/system.string.endswith
  460. .. _string.Equals: https://learn.microsoft.com/en-us/dotnet/api/system.string.equals
  461. .. _string.IndexOf: https://learn.microsoft.com/en-us/dotnet/api/system.string.indexof
  462. .. _string.IndexOfAny: https://learn.microsoft.com/en-us/dotnet/api/system.string.indexofany
  463. .. _string.Insert: https://learn.microsoft.com/en-us/dotnet/api/system.string.insert
  464. .. _string.IsNullOrEmpty: https://learn.microsoft.com/en-us/dotnet/api/system.string.isnullorempty
  465. .. _string.IsNullOrWhiteSpace: https://learn.microsoft.com/en-us/dotnet/api/system.string.isnullorwhitespace
  466. .. _string.Join: https://learn.microsoft.com/en-us/dotnet/api/system.string.join
  467. .. _string.LastIndexOf: https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexof
  468. .. _string.LastIndexOfAny: https://learn.microsoft.com/en-us/dotnet/api/system.string.lastindexofany
  469. .. _string.Length: https://learn.microsoft.com/en-us/dotnet/api/system.string.length
  470. .. _string.PadLeft: https://learn.microsoft.com/en-us/dotnet/api/system.string.padleft
  471. .. _string.PadRight: https://learn.microsoft.com/en-us/dotnet/api/system.string.padright
  472. .. _string.Remove: https://learn.microsoft.com/en-us/dotnet/api/system.string.remove
  473. .. _string.Replace: https://learn.microsoft.com/en-us/dotnet/api/system.string.replace
  474. .. _string.Split: https://learn.microsoft.com/en-us/dotnet/api/system.string.split
  475. .. _string.StartsWith: https://learn.microsoft.com/en-us/dotnet/api/system.string.startswith
  476. .. _string.Substring: https://learn.microsoft.com/en-us/dotnet/api/system.string.substring
  477. .. _string.Trim: https://learn.microsoft.com/en-us/dotnet/api/system.string.trim
  478. .. _string.TrimEnd: https://learn.microsoft.com/en-us/dotnet/api/system.string.trimend
  479. .. _string.TrimStart: https://learn.microsoft.com/en-us/dotnet/api/system.string.trimstart
  480. .. _string.ToLower: https://learn.microsoft.com/en-us/dotnet/api/system.string.tolower
  481. .. _string.ToUpper: https://learn.microsoft.com/en-us/dotnet/api/system.string.toupper
  482. .. _StringBuilder: https://learn.microsoft.com/en-us/dotnet/api/system.text.stringbuilder
  483. .. _System.Convert.FromHexString: https://learn.microsoft.com/en-us/dotnet/api/system.convert.fromhexstring
  484. .. _System.Convert.ToHexString: https://learn.microsoft.com/en-us/dotnet/api/system.convert.tohexstring
  485. .. _System.Globalization.NumberStyles.HexNumber: https://learn.microsoft.com/en-us/dotnet/api/system.globalization.numberstyles#system-globalization-numberstyles-hexnumber
  486. .. _System.IO.Path: https://learn.microsoft.com/en-us/dotnet/api/system.io.path
  487. .. _System.Security.Cryptography.MD5.HashData: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.md5.hashdata
  488. .. _System.Security.Cryptography.SHA1.HashData: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha1.hashdata
  489. .. _System.Security.Cryptography.SHA256.HashData: https://learn.microsoft.com/en-us/dotnet/api/system.security.cryptography.sha256.hashdata
  490. .. _System.Text.Encoding.ASCII.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.asciiencoding.getbytes
  491. .. _System.Text.Encoding.ASCII.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.asciiencoding.getstring
  492. .. _System.Text.Encoding.UTF16.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.unicodeencoding.getbytes
  493. .. _System.Text.Encoding.UTF16.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.unicodeencoding.getstring
  494. .. _System.Text.Encoding.UTF32.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf32encoding.getbytes
  495. .. _System.Text.Encoding.UTF32.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf32encoding.getstring
  496. .. _System.Text.Encoding.UTF8.GetBytes: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf8encoding.getbytes
  497. .. _System.Text.Encoding.UTF8.GetString: https://learn.microsoft.com/en-us/dotnet/api/system.text.utf8encoding.getstring
  498. .. _System.Uri.EscapeDataString: https://learn.microsoft.com/en-us/dotnet/api/system.uri.escapedatastring
  499. .. _System.Uri.UnescapeDataString: https://learn.microsoft.com/en-us/dotnet/api/system.uri.unescapedatastring
  500. NodePath
  501. --------
  502. The following method was converted to a property with a different name:
  503. ==================== ==============================================================
  504. GDScript C#
  505. ==================== ==============================================================
  506. ``is_empty()`` ``IsEmpty``
  507. ==================== ==============================================================
  508. Signal
  509. ------
  510. The following methods were converted to properties with their respective names changed:
  511. ==================== ==============================================================
  512. GDScript C#
  513. ==================== ==============================================================
  514. ``get_name()`` ``Name``
  515. ``get_object()`` ``Owner``
  516. ==================== ==============================================================
  517. The ``Signal`` type implements the awaitable pattern which means it can be used with
  518. the ``await`` keyword. See :ref:`doc_c_sharp_differences_await`.
  519. Instead of using the ``Signal`` type, the recommended way to use Godot signals in C# is
  520. to use the generated C# events. See :ref:`doc_c_sharp_signals`.
  521. Callable
  522. --------
  523. The following methods were converted to properties with their respective names changed:
  524. ==================== ==============================================================
  525. GDScript C#
  526. ==================== ==============================================================
  527. ``get_object()`` ``Target``
  528. ``get_method()`` ``Method``
  529. ==================== ==============================================================
  530. Currently C# supports ``Callable`` if one of the following holds:
  531. * ``Callable`` was created using the C# ``Callable`` type.
  532. * ``Callable`` is a basic version of the engine's ``Callable``. Custom ``Callable``\ s
  533. are unsupported. A ``Callable`` is custom when any of the following holds:
  534. * ``Callable`` has bound information (``Callable``\ s created with ``bind``/``unbind`` are unsupported).
  535. * ``Callable`` was created from other languages through the GDExtension API.
  536. Some methods such as ``bind`` and ``unbind`` are not implemented, use lambdas instead:
  537. .. code-block:: csharp
  538. string name = "John Doe";
  539. Callable callable = Callable.From(() => SayHello(name));
  540. void SayHello(string name)
  541. {
  542. GD.Print($"Hello {name}");
  543. }
  544. The lambda captures the ``name`` variable so it can be bound to the ``SayHello`` method.
  545. RID
  546. ---
  547. This type is named ``Rid`` in C# to follow the .NET naming convention.
  548. The following methods were converted to properties with their respective names changed:
  549. ==================== ==============================================================
  550. GDScript C#
  551. ==================== ==============================================================
  552. ``get_id()`` ``Id``
  553. ``is_valid()`` ``IsValid``
  554. ==================== ==============================================================
  555. Basis
  556. -----
  557. Structs cannot have parameterless constructors in C#. Therefore, ``new Basis()``
  558. initializes all primitive members to their default value. Use ``Basis.Identity``
  559. for the equivalent of ``Basis()`` in GDScript and C++.
  560. The following method was converted to a property with a different name:
  561. ==================== ==============================================================
  562. GDScript C#
  563. ==================== ==============================================================
  564. ``get_scale()`` ``Scale``
  565. ==================== ==============================================================
  566. Transform2D
  567. -----------
  568. Structs cannot have parameterless constructors in C#. Therefore, ``new Transform2D()``
  569. initializes all primitive members to their default value.
  570. Please use ``Transform2D.Identity`` for the equivalent of ``Transform2D()`` in GDScript and C++.
  571. The following methods were converted to properties with their respective names changed:
  572. ==================== ==============================================================
  573. GDScript C#
  574. ==================== ==============================================================
  575. ``get_rotation()`` ``Rotation``
  576. ``get_scale()`` ``Scale``
  577. ``get_skew()`` ``Skew``
  578. ==================== ==============================================================
  579. Transform3D
  580. -----------
  581. Structs cannot have parameterless constructors in C#. Therefore, ``new Transform3D()``
  582. initializes all primitive members to their default value.
  583. Please use ``Transform3D.Identity`` for the equivalent of ``Transform3D()`` in GDScript and C++.
  584. The following methods were converted to properties with their respective names changed:
  585. ==================== ==============================================================
  586. GDScript C#
  587. ==================== ==============================================================
  588. ``get_rotation()`` ``Rotation``
  589. ``get_scale()`` ``Scale``
  590. ==================== ==============================================================
  591. Rect2
  592. -----
  593. The following field was converted to a property with a *slightly* different name:
  594. ================ ==================================================================
  595. GDScript C#
  596. ================ ==================================================================
  597. ``end`` ``End``
  598. ================ ==================================================================
  599. The following method was converted to a property with a different name:
  600. ================ ==================================================================
  601. GDScript C#
  602. ================ ==================================================================
  603. ``get_area()`` ``Area``
  604. ================ ==================================================================
  605. Rect2i
  606. ------
  607. This type is named ``Rect2I`` in C# to follow the .NET naming convention.
  608. The following field was converted to a property with a *slightly* different name:
  609. ================ ==================================================================
  610. GDScript C#
  611. ================ ==================================================================
  612. ``end`` ``End``
  613. ================ ==================================================================
  614. The following method was converted to a property with a different name:
  615. ================ ==================================================================
  616. GDScript C#
  617. ================ ==================================================================
  618. ``get_area()`` ``Area``
  619. ================ ==================================================================
  620. AABB
  621. ----
  622. This type is named ``Aabb`` in C# to follow the .NET naming convention.
  623. The following method was converted to a property with a different name:
  624. ================ ==================================================================
  625. GDScript C#
  626. ================ ==================================================================
  627. ``get_volume()`` ``Volume``
  628. ================ ==================================================================
  629. Quaternion
  630. ----------
  631. Structs cannot have parameterless constructors in C#. Therefore, ``new Quaternion()``
  632. initializes all primitive members to their default value.
  633. Please use ``Quaternion.Identity`` for the equivalent of ``Quaternion()`` in GDScript and C++.
  634. Projection
  635. ----------
  636. Structs cannot have parameterless constructors in C#. Therefore, ``new Projection()``
  637. initializes all primitive members to their default value.
  638. Please use ``Projection.Identity`` for the equivalent of ``Projection()`` in GDScript and C++.
  639. Color
  640. -----
  641. Structs cannot have parameterless constructors in C#. Therefore, ``new Color()``
  642. initializes all primitive members to their default value (which represents the transparent black color).
  643. Please use ``Colors.Black`` for the equivalent of ``Color()`` in GDScript and C++.
  644. The global ``Color8`` method to construct a Color from bytes is available as a static method
  645. in the Color type.
  646. The Color constants are available in the ``Colors`` static class as readonly properties.
  647. The following method was converted to a property with a different name:
  648. ==================== ==============================================================
  649. GDScript C#
  650. ==================== ==============================================================
  651. ``get_luminance()`` ``Luminance``
  652. ==================== ==============================================================
  653. The following method was converted to a method with a different name:
  654. ==================== ==============================================================
  655. GDScript C#
  656. ==================== ==============================================================
  657. ``html(String)`` ``FromHtml(ReadOnlySpan<char>)``
  658. ==================== ==============================================================
  659. The following methods are available as constructors:
  660. ==================== ==============================================================
  661. GDScript C#
  662. ==================== ==============================================================
  663. ``hex(int)`` ``Color(uint)``
  664. ``hex64(int)`` ``Color(ulong)``
  665. ==================== ==============================================================
  666. Array
  667. -----
  668. The equivalent of packed arrays are ``System.Array``.
  669. See also :ref:`PackedArray in C# <doc_c_sharp_collections_packedarray>`.
  670. Use ``Godot.Collections.Array`` for an untyped ``Variant`` array.
  671. ``Godot.Collections.Array<T>`` is a type-safe wrapper around ``Godot.Collections.Array``.
  672. See also :ref:`Array in C# <doc_c_sharp_collections_array>`.
  673. Dictionary
  674. ----------
  675. Use ``Godot.Collections.Dictionary`` for an untyped ``Variant`` dictionary.
  676. ``Godot.Collections.Dictionary<TKey, TValue>`` is a type-safe wrapper around ``Godot.Collections.Dictionary``.
  677. See also :ref:`Dictionary in C# <doc_c_sharp_collections_dictionary>`.
  678. Variant
  679. -------
  680. ``Godot.Variant`` is used to represent Godot's native :ref:`Variant <class_Variant>` type.
  681. Any :ref:`Variant-compatible type <c_sharp_variant_compatible_types>` can be converted from/to it.
  682. See also: :ref:`doc_c_sharp_variant`.
  683. Communicating with other scripting languages
  684. --------------------------------------------
  685. This is explained extensively in :ref:`doc_cross_language_scripting`.
  686. .. _doc_c_sharp_differences_await:
  687. ``await`` keyword
  688. -----------------
  689. Something similar to GDScript's ``await`` keyword can be achieved with C#'s
  690. `await keyword <https://docs.microsoft.com/en-US/dotnet/csharp/language-reference/keywords/await>`_.
  691. The ``await`` keyword in C# can be used with any awaitable expression. It's commonly
  692. used with operands of the types `Task`_, `Task<TResult>`_, `ValueTask`_, or `ValueTask<TResult>`_.
  693. An expression ``t`` is awaitable if one of the following holds:
  694. * ``t`` is of compile-time type ``dynamic``.
  695. * ``t`` has an accessible instance or extension method called ``GetAwaiter`` with no
  696. parameters and no type parameters, and a return type ``A`` for which all of the
  697. following hold:
  698. * ``A`` implements the interface ``System.Runtime.CompilerServices.INotifyCompletion``.
  699. * ``A`` has an accessible, readable instance property ``IsCompleted`` of type ``bool``.
  700. * ``A`` has an accessible instance method ``GetResult`` with no parameters and no type
  701. parameters.
  702. .. _Task: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task
  703. .. _Task<TResult>: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1
  704. .. _ValueTask: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask
  705. .. _ValueTask<TResult>: https://learn.microsoft.com/en-us/dotnet/api/system.threading.tasks.valuetask-1
  706. An equivalent of awaiting a signal in GDScript can be achieved with the ``await`` keyword and
  707. ``GodotObject.ToSignal``.
  708. Example:
  709. .. code-block:: csharp
  710. public async Task SomeFunction()
  711. {
  712. await ToSignal(timer, Timer.SignalName.Timeout);
  713. GD.Print("After timeout");
  714. }