c_sharp_differences.rst 42 KB

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