c_sharp_collections.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. ``PackedVector4Array`` ``Vector4[]``
  67. ``PackedColorArray`` ``Color[]``
  68. ====================== ==============================================================
  69. Other C# arrays are not supported by the Godot C# API since a packed array equivalent
  70. does not exist. See the list of :ref:`c_sharp_variant_compatible_types`.
  71. .. _doc_c_sharp_collections_array:
  72. Array
  73. ^^^^^
  74. Godot arrays are implemented as an array of ``Variant`` and can contain several elements
  75. of any type. In C#, the equivalent type is ``Godot.Collections.Array``.
  76. The generic ``Godot.Collections.Array<T>`` type allows restricting the element type to
  77. a :ref:`Variant-compatible type <c_sharp_variant_compatible_types>`.
  78. An untyped ``Godot.Collections.Array`` can be converted to a typed array using the
  79. ``Godot.Collections.Array<T>(Godot.Collections.Array)`` constructor.
  80. .. note::
  81. Despite the name, Godot arrays are more similar to the C# collection
  82. ``List<T>`` than ``System.Array``. Their size is not fixed and can grow
  83. or shrink as elements are added/removed from the collection.
  84. List of Godot's Array methods and their equivalent in C#:
  85. ======================= ==============================================================
  86. GDScript C#
  87. ======================= ==============================================================
  88. all `System.Linq.Enumerable.All`_
  89. any `System.Linq.Enumerable.Any`_
  90. append Add
  91. append_array AddRange
  92. assign Clear and AddRange
  93. back ``Array[^1]`` or `System.Linq.Enumerable.Last`_ or `System.Linq.Enumerable.LastOrDefault`_
  94. bsearch BinarySearch
  95. bsearch_custom N/A
  96. clear Clear
  97. count `System.Linq.Enumerable.Count`_
  98. duplicate Duplicate
  99. erase Remove
  100. fill Fill
  101. filter Use `System.Linq.Enumerable.Where`_
  102. find IndexOf
  103. front ``Array[0]`` or `System.Linq.Enumerable.First`_ or `System.Linq.Enumerable.FirstOrDefault`_
  104. get_typed_builtin N/A
  105. get_typed_class_name N/A
  106. get_typed_script N/A
  107. has Contains
  108. hash GD.Hash
  109. insert Insert
  110. is_empty Use ``Count == 0``
  111. is_read_only IsReadOnly
  112. is_same_typed N/A
  113. is_typed N/A
  114. make_read_only MakeReadOnly
  115. map `System.Linq.Enumerable.Select`_
  116. max Max
  117. min Min
  118. pick_random PickRandom (Consider using `System.Random`_)
  119. pop_at ``Array[i]`` with ``RemoveAt(i)``
  120. pop_back ``Array[^1]`` with ``RemoveAt(Count - 1)``
  121. pop_front ``Array[0]`` with ``RemoveAt(0)``
  122. push_back ``Insert(Count, item)``
  123. push_front ``Insert(0, item)``
  124. reduce `System.Linq.Enumerable.Aggregate`_
  125. remove_at RemoveAt
  126. resize Resize
  127. reverse Reverse
  128. rfind LastIndexOf
  129. shuffle Shuffle
  130. size Count
  131. slice Slice
  132. sort Sort
  133. sort_custom `System.Linq.Enumerable.OrderBy`_
  134. operator != !RecursiveEqual
  135. operator + operator +
  136. operator < N/A
  137. operator <= N/A
  138. operator == RecursiveEqual
  139. operator > N/A
  140. operator >= N/A
  141. operator [] Array[int] indexer
  142. ======================= ==============================================================
  143. .. _System.Random: https://learn.microsoft.com/en-us/dotnet/api/system.random
  144. .. _System.Linq.Enumerable.Aggregate: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.aggregate
  145. .. _System.Linq.Enumerable.All: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.all
  146. .. _System.Linq.Enumerable.Any: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.any
  147. .. _System.Linq.Enumerable.Count: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.count
  148. .. _System.Linq.Enumerable.First: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.first
  149. .. _System.Linq.Enumerable.FirstOrDefault: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.firstordefault
  150. .. _System.Linq.Enumerable.Last: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.last
  151. .. _System.Linq.Enumerable.LastOrDefault: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.lastordefault
  152. .. _System.Linq.Enumerable.OrderBy: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.orderby
  153. .. _System.Linq.Enumerable.Select: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.select
  154. .. _System.Linq.Enumerable.Where: https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where
  155. .. _doc_c_sharp_collections_dictionary:
  156. Dictionary
  157. ^^^^^^^^^^
  158. Godot dictionaries are implemented as a dictionary with ``Variant`` keys and values.
  159. In C#, the equivalent type is ``Godot.Collections.Dictionary``.
  160. The generic ``Godot.Collections.Dictionary<TKey, TValue>`` type allows restricting the key
  161. and value types to a :ref:`Variant-compatible type <c_sharp_variant_compatible_types>`.
  162. An untyped ``Godot.Collections.Dictionary`` can be converted to a typed dictionary using the
  163. ``Godot.Collections.Dictionary<TKey, TValue>(Godot.Collections.Dictionary)`` constructor.
  164. .. tip::
  165. If you need a dictionary where the key is typed but not the value, use
  166. ``Variant`` as the ``TValue`` generic parameter of the typed dictionary.
  167. .. code-block:: csharp
  168. // The keys must be string, but the values can be any Variant-compatible type.
  169. var dictionary = new Godot.Collections.Dictionary<string, Variant>();
  170. List of Godot's Dictionary methods and their equivalent in C#:
  171. ======================= ==============================================================
  172. GDScript C#
  173. ======================= ==============================================================
  174. clear Clear
  175. duplicate Duplicate
  176. erase Remove
  177. find_key N/A
  178. get Dictionary[Variant] indexer or TryGetValue
  179. has ContainsKey
  180. has_all N/A
  181. hash GD.Hash
  182. is_empty Use ``Count == 0``
  183. is_read_only IsReadOnly
  184. keys Keys
  185. make_read_only MakeReadOnly
  186. merge Merge
  187. size Count
  188. values Values
  189. operator != !RecursiveEqual
  190. operator == RecursiveEqual
  191. operator [] Dictionary[Variant] indexer, Add or TryGetValue
  192. ======================= ==============================================================