c_sharp_differences.rst 41 KB

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