c_sharp_collections.rst 11 KB

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