c_sharp_collections.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. .. _doc_c_sharp_collections:
  2. C# collections
  3. ==============
  4. Choose a collection
  5. -------------------
  6. The .NET base class library contains multiple collection types that can be
  7. used to store and manipulate data. Godot also provide some collection types.
  8. The main difference between the `.NET collections <https://learn.microsoft.com/en-us/dotnet/standard/collections/>`_
  9. and the Godot collections is that the .NET collections are implemented in C# while
  10. the Godot collections are implemented in C++ and the Godot C# API is a wrapper over it,
  11. this is an important distinction since it means every operation on a Godot collection
  12. requires marshaling which can be expensive especially inside a loop.
  13. Due to the performance implications, using Godot collections is only recommended
  14. when absolutely necessary (such as interacting with the Godot API). Godot only
  15. understands its own collection types, so it's required to use them when talking
  16. to the engine.
  17. If you have a collection of elements that don't need to be passed to a Godot API,
  18. using a .NET collection would be more performant.
  19. .. tip::
  20. It's also possible to convert between .NET collections and Godot collections.
  21. The Godot collections contain constructors from generic .NET collection interfaces
  22. that copy their elements, and the Godot collections can be used with the
  23. `LINQ <https://learn.microsoft.com/en-us/dotnet/standard/linq>`_
  24. ``ToList``, ``ToArray`` and ``ToDictionary`` methods. But keep in mind this conversion
  25. requires marshaling every element in the collection and copies it to a new collection
  26. so it can be expensive.
  27. Despite this, the Godot collections are optimized to try and avoid unnecessary
  28. marshaling, so methods like ``Sort`` or ``Reverse`` are implemented with a single
  29. interop call and don't need to marshal every element. Keep an eye out for generic APIs
  30. that take collection interfaces like `LINQ <https://learn.microsoft.com/en-us/dotnet/standard/linq>`_
  31. because every method requires iterating the collection and, therefore, marshaling
  32. every element. Prefer using the instance methods of the Godot collections when possible.
  33. To choose which collection type to use for each situation, consider the following questions:
  34. * Does your collection need to interact with the Godot engine?
  35. (e.g.: the type of an exported property, calling a Godot method).
  36. * If yes, since Godot only supports :ref:`Variant-compatible <doc_c_sharp_variant>`
  37. types, use a Godot collection.
  38. * If not, consider `choosing an appropiate .NET collection <https://learn.microsoft.com/en-us/dotnet/standard/collections/selecting-a-collection-class>`_.
  39. * Do you need a Godot collection that represents a list or sequential set of data?
  40. * Godot :ref:`arrays <doc_c_sharp_collections_array>` are similar to the C# collection ``List<T>``.
  41. * Godot :ref:`packed arrays <doc_c_sharp_collections_packedarray>` are more memory-efficient arrays,
  42. in C# use one of the supported ``System.Array`` types.
  43. * Do you need a Godot collection that maps a set of keys to a set of values?
  44. * Godot :ref:`dictionaries <doc_c_sharp_collections_dictionary>` store pairs of keys and values
  45. and allow easy access to the values by their associated key.
  46. Godot collections
  47. -----------------
  48. .. _doc_c_sharp_collections_packedarray:
  49. PackedArray
  50. ^^^^^^^^^^^
  51. Godot packed arrays are implemented as an array of a specific type, allowing it to be
  52. more tightly packed as each element has the size of the specific type, not ``Variant``.
  53. In C#, packed arrays are replaced by ``System.Array``:
  54. ====================== ==============================================================
  55. GDScript C#
  56. ====================== ==============================================================
  57. ``PackedInt32Array`` ``int[]``
  58. ``PackedInt64Array`` ``long[]``
  59. ``PackedByteArray`` ``byte[]``
  60. ``PackedFloat32Array`` ``float[]``
  61. ``PackedFloat64Array`` ``double[]``
  62. ``PackedStringArray`` ``string[]``
  63. ``PackedColorArray`` ``Color[]``
  64. ``PackedVector2Array`` ``Vector2[]``
  65. ``PackedVector3Array`` ``Vector3[]``
  66. ====================== ==============================================================
  67. Other C# arrays are not supported by the Godot C# API since a packed array equivalent
  68. does not exist. See :ref:`Variant <doc_c_sharp_variant>` for a list of all the compatible
  69. types.
  70. .. _doc_c_sharp_collections_array:
  71. Array
  72. ^^^^^
  73. Godot arrays are implemented as an array of ``Variant`` and can contain several elements
  74. of any type. In C#, the equivalent type is ``Godot.Collections.Array``.
  75. The generic ``Godot.Collections.Array<T>`` type allows restricting the element type to
  76. a :ref:`Variant-compatible <doc_c_sharp_variant>` type.
  77. An untyped ``Godot.Collections.Array`` can be converted to a typed array using the
  78. ``Godot.Collections.Array<T>(Godot.Collections.Array)`` constructor.
  79. .. note::
  80. Despite the name, Godot arrays are more similar to the C# collection
  81. ``List<T>`` than ``System.Array``. Their size is not fixed and can grow
  82. or shrink as elements are added/removed from the collection.
  83. List of Godot's Array methods and their equivalent in C#:
  84. ======================= ==============================================================
  85. GDScript C#
  86. ======================= ==============================================================
  87. all `System.Linq.Enumerable.All`_
  88. any `System.Linq.Enumerable.Any`_
  89. append Add
  90. append_array AddRange
  91. back ``Array[^1]`` or `System.Linq.Enumerable.Last`_ or `System.Linq.Enumerable.LastOrDefault`_
  92. bsearch BinarySearch
  93. bsearch_custom N/A
  94. clear Clear
  95. count `System.Linq.Enumerable.Count`_
  96. duplicate Duplicate
  97. erase Remove
  98. fill Fill
  99. filter Use `System.Linq.Enumerable.Where`_
  100. find IndexOf
  101. front ``Array[0]`` or `System.Linq.Enumerable.First`_ or `System.Linq.Enumerable.FirstOrDefault`_
  102. get_typed_builtin N/A
  103. get_typed_class_name N/A
  104. get_typed_script N/A
  105. has Contains
  106. hash GD.Hash
  107. insert Insert
  108. is_empty Use ``Count == 0``
  109. is_read_only IsReadOnly
  110. is_typed N/A
  111. make_read_only MakeReadOnly
  112. map `System.Linq.Enumerable.Select`_
  113. max Max
  114. min Min
  115. pick_random PickRandom (Consider using `System.Random`_)
  116. pop_at ``Array[i]`` with ``RemoveAt(i)``
  117. pop_back ``Array[^1]`` with ``RemoveAt(Count - 1)``
  118. pop_front ``Array[0]`` with ``RemoveAt(0)``
  119. push_back ``Insert(Count, item)``
  120. push_front ``Insert(0, item)``
  121. reduce `System.Linq.Enumerable.Aggregate`_
  122. remove_at RemoveAt
  123. resize Resize
  124. reverse Reverse
  125. rfind LastIndexOf
  126. shuffle Shuffle
  127. size Count
  128. slice Slice
  129. sort Sort
  130. sort_custom `System.Linq.Enumerable.OrderBy`_
  131. typed_assign N/A
  132. operator != !RecursiveEqual
  133. operator + operator +
  134. operator < N/A
  135. operator <= N/A
  136. operator == RecursiveEqual
  137. operator > N/A
  138. operator >= N/A
  139. operator [] Array[int] indexer
  140. ======================= ==============================================================
  141. .. _System.Random: https://learn.microsoft.com/en-us/dotnet/api/system.random
  142. .. _System.Linq.Enumerable.Aggregate: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate
  143. .. _System.Linq.Enumerable.All: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.all
  144. .. _System.Linq.Enumerable.Any: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any
  145. .. _System.Linq.Enumerable.Count: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.count
  146. .. _System.Linq.Enumerable.First: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.first
  147. .. _System.Linq.Enumerable.FirstOrDefault: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault
  148. .. _System.Linq.Enumerable.Last: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.last
  149. .. _System.Linq.Enumerable.LastOrDefault: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.lastordefault
  150. .. _System.Linq.Enumerable.OrderBy: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby
  151. .. _System.Linq.Enumerable.Select: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select
  152. .. _System.Linq.Enumerable.Where: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where
  153. .. _doc_c_sharp_collections_dictionary:
  154. Dictionary
  155. ^^^^^^^^^^
  156. Godot dictionaries are implemented as a dictionary with ``Variant`` keys and values.
  157. In C#, the equivalent type is ``Godot.Collections.Dictionary``.
  158. The generic ``Godot.Collections.Dictionary<TKey, TValue>`` type allows restricting the key
  159. and value types to a :ref:`Variant-compatible <doc_c_sharp_variant>` type.
  160. An untyped ``Godot.Collections.Dictionary`` can be converted to a typed dictionary using the
  161. ``Godot.Collections.Dictionary<TKey, TValue>(Godot.Collections.Dictionary)`` constructor.
  162. .. tip::
  163. If you need a dictionary where the key is typed but not the value, use
  164. ``Variant`` as the ``TValue`` generic parameter of the typed dictionary.
  165. .. code-block:: csharp
  166. // The keys must be string, but the values can be any Variant-compatible type.
  167. var dictionary = new Godot.Collections.Dictionary<string, Variant>();
  168. List of Godot's Dictionary methods and their equivalent in C#:
  169. ======================= ==============================================================
  170. GDScript C#
  171. ======================= ==============================================================
  172. clear Clear
  173. duplicate Duplicate
  174. erase Remove
  175. find_key N/A
  176. get Dictionary[Variant] indexer or TryGetValue
  177. has ContainsKey
  178. has_all N/A
  179. hash GD.Hash
  180. is_empty Use ``Count == 0``
  181. is_read_only IsReadOnly
  182. keys Keys
  183. make_read_only MakeReadOnly
  184. merge Merge
  185. size Count
  186. values Values
  187. operator != !RecursiveEqual
  188. operator == RecursiveEqual
  189. operator [] Dictionary[Variant] indexer, Add or TryGetValue
  190. ======================= ==============================================================