Array.cs 71 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Linq;
  6. using System.Runtime.CompilerServices;
  7. using Godot.NativeInterop;
  8. namespace Godot.Collections
  9. {
  10. /// <summary>
  11. /// Wrapper around Godot's Array class, an array of Variant
  12. /// typed elements allocated in the engine in C++. Useful when
  13. /// interfacing with the engine. Otherwise prefer .NET collections
  14. /// such as <see cref="System.Array"/> or <see cref="List{T}"/>.
  15. /// </summary>
  16. public sealed class Array :
  17. IList<Variant>,
  18. IReadOnlyList<Variant>,
  19. ICollection,
  20. IDisposable
  21. {
  22. internal godot_array.movable NativeValue;
  23. private WeakReference<IDisposable> _weakReferenceToSelf;
  24. /// <summary>
  25. /// Constructs a new empty <see cref="Array"/>.
  26. /// </summary>
  27. public Array()
  28. {
  29. NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
  30. _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
  31. }
  32. /// <summary>
  33. /// Constructs a new <see cref="Array"/> from the given collection's elements.
  34. /// </summary>
  35. /// <param name="collection">The collection of elements to construct from.</param>
  36. /// <returns>A new Godot Array.</returns>
  37. public Array(IEnumerable<Variant> collection) : this()
  38. {
  39. if (collection == null)
  40. throw new ArgumentNullException(nameof(collection));
  41. foreach (Variant element in collection)
  42. Add(element);
  43. }
  44. /// <summary>
  45. /// Constructs a new <see cref="Array"/> from the given objects.
  46. /// </summary>
  47. /// <param name="array">The objects to put in the new array.</param>
  48. /// <returns>A new Godot Array.</returns>
  49. public Array(Variant[] array) : this()
  50. {
  51. if (array == null)
  52. throw new ArgumentNullException(nameof(array));
  53. NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
  54. _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
  55. int length = array.Length;
  56. Resize(length);
  57. for (int i = 0; i < length; i++)
  58. this[i] = array[i];
  59. }
  60. public Array(Span<StringName> array) : this()
  61. {
  62. if (array == null)
  63. throw new ArgumentNullException(nameof(array));
  64. NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
  65. _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
  66. int length = array.Length;
  67. Resize(length);
  68. for (int i = 0; i < length; i++)
  69. this[i] = array[i];
  70. }
  71. public Array(Span<NodePath> array) : this()
  72. {
  73. if (array == null)
  74. throw new ArgumentNullException(nameof(array));
  75. NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
  76. _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
  77. int length = array.Length;
  78. Resize(length);
  79. for (int i = 0; i < length; i++)
  80. this[i] = array[i];
  81. }
  82. public Array(Span<Rid> array) : this()
  83. {
  84. if (array == null)
  85. throw new ArgumentNullException(nameof(array));
  86. NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
  87. _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
  88. int length = array.Length;
  89. Resize(length);
  90. for (int i = 0; i < length; i++)
  91. this[i] = array[i];
  92. }
  93. // We must use ReadOnlySpan instead of Span here as this can accept implicit conversions
  94. // from derived types (e.g.: Node[]). Implicit conversion from Derived[] to Base[] are
  95. // fine as long as the array is not mutated. However, Span does this type checking at
  96. // instantiation, so it's not possible to use it even when not mutating anything.
  97. // ReSharper disable once RedundantNameQualifier
  98. public Array(ReadOnlySpan<GodotObject> array) : this()
  99. {
  100. if (array == null)
  101. throw new ArgumentNullException(nameof(array));
  102. NativeValue = (godot_array.movable)NativeFuncs.godotsharp_array_new();
  103. _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
  104. int length = array.Length;
  105. Resize(length);
  106. for (int i = 0; i < length; i++)
  107. this[i] = array[i];
  108. }
  109. private Array(godot_array nativeValueToOwn)
  110. {
  111. NativeValue = (godot_array.movable)(nativeValueToOwn.IsAllocated ?
  112. nativeValueToOwn :
  113. NativeFuncs.godotsharp_array_new());
  114. _weakReferenceToSelf = DisposablesTracker.RegisterDisposable(this);
  115. }
  116. // Explicit name to make it very clear
  117. internal static Array CreateTakingOwnershipOfDisposableValue(godot_array nativeValueToOwn)
  118. => new Array(nativeValueToOwn);
  119. ~Array()
  120. {
  121. Dispose(false);
  122. }
  123. /// <summary>
  124. /// Disposes of this <see cref="Array"/>.
  125. /// </summary>
  126. public void Dispose()
  127. {
  128. Dispose(true);
  129. GC.SuppressFinalize(this);
  130. }
  131. public void Dispose(bool disposing)
  132. {
  133. // Always dispose `NativeValue` even if disposing is true
  134. NativeValue.DangerousSelfRef.Dispose();
  135. if (_weakReferenceToSelf != null)
  136. {
  137. DisposablesTracker.UnregisterDisposable(_weakReferenceToSelf);
  138. }
  139. }
  140. /// <summary>
  141. /// Returns a copy of the <see cref="Array"/>.
  142. /// If <paramref name="deep"/> is <see langword="true"/>, a deep copy if performed:
  143. /// all nested arrays and dictionaries are duplicated and will not be shared with
  144. /// the original array. If <see langword="false"/>, a shallow copy is made and
  145. /// references to the original nested arrays and dictionaries are kept, so that
  146. /// modifying a sub-array or dictionary in the copy will also impact those
  147. /// referenced in the source array. Note that any <see cref="GodotObject"/> derived
  148. /// elements will be shallow copied regardless of the <paramref name="deep"/>
  149. /// setting.
  150. /// </summary>
  151. /// <param name="deep">If <see langword="true"/>, performs a deep copy.</param>
  152. /// <returns>A new Godot Array.</returns>
  153. public Array Duplicate(bool deep = false)
  154. {
  155. godot_array newArray;
  156. var self = (godot_array)NativeValue;
  157. NativeFuncs.godotsharp_array_duplicate(ref self, deep.ToGodotBool(), out newArray);
  158. return CreateTakingOwnershipOfDisposableValue(newArray);
  159. }
  160. /// <summary>
  161. /// Assigns the given value to all elements in the array. This can typically be
  162. /// used together with <see cref="Resize(int)"/> to create an array with a given
  163. /// size and initialized elements.
  164. /// Note: If <paramref name="value"/> is of a reference type (<see cref="GodotObject"/>
  165. /// derived, <see cref="Array"/> or <see cref="Dictionary"/>, etc.) then the array
  166. /// is filled with the references to the same object, i.e. no duplicates are
  167. /// created.
  168. /// </summary>
  169. /// <example>
  170. /// <code>
  171. /// var array = new Godot.Collections.Array();
  172. /// array.Resize(10);
  173. /// array.Fill(0); // Initialize the 10 elements to 0.
  174. /// </code>
  175. /// </example>
  176. /// <exception cref="InvalidOperationException">
  177. /// The array is read-only.
  178. /// </exception>
  179. /// <param name="value">The value to fill the array with.</param>
  180. public void Fill(Variant value)
  181. {
  182. ThrowIfReadOnly();
  183. godot_variant variantValue = (godot_variant)value.NativeVar;
  184. var self = (godot_array)NativeValue;
  185. NativeFuncs.godotsharp_array_fill(ref self, variantValue);
  186. }
  187. /// <summary>
  188. /// Returns the maximum value contained in the array if all elements are of
  189. /// comparable types. If the elements can't be compared, <see langword="null"/>
  190. /// is returned.
  191. /// </summary>
  192. /// <returns>The maximum value contained in the array.</returns>
  193. public Variant Max()
  194. {
  195. godot_variant resVariant;
  196. var self = (godot_array)NativeValue;
  197. NativeFuncs.godotsharp_array_max(ref self, out resVariant);
  198. return Variant.CreateTakingOwnershipOfDisposableValue(resVariant);
  199. }
  200. /// <summary>
  201. /// Returns the minimum value contained in the array if all elements are of
  202. /// comparable types. If the elements can't be compared, <see langword="null"/>
  203. /// is returned.
  204. /// </summary>
  205. /// <returns>The minimum value contained in the array.</returns>
  206. public Variant Min()
  207. {
  208. godot_variant resVariant;
  209. var self = (godot_array)NativeValue;
  210. NativeFuncs.godotsharp_array_min(ref self, out resVariant);
  211. return Variant.CreateTakingOwnershipOfDisposableValue(resVariant);
  212. }
  213. /// <summary>
  214. /// Returns a random value from the target array.
  215. /// </summary>
  216. /// <example>
  217. /// <code>
  218. /// var array = new Godot.Collections.Array { 1, 2, 3, 4 };
  219. /// GD.Print(array.PickRandom()); // Prints either of the four numbers.
  220. /// </code>
  221. /// </example>
  222. /// <returns>A random element from the array.</returns>
  223. public Variant PickRandom()
  224. {
  225. godot_variant resVariant;
  226. var self = (godot_array)NativeValue;
  227. NativeFuncs.godotsharp_array_pick_random(ref self, out resVariant);
  228. return Variant.CreateTakingOwnershipOfDisposableValue(resVariant);
  229. }
  230. /// <summary>
  231. /// Compares this <see cref="Array"/> against the <paramref name="other"/>
  232. /// <see cref="Array"/> recursively. Returns <see langword="true"/> if the
  233. /// sizes and contents of the arrays are equal, <see langword="false"/>
  234. /// otherwise.
  235. /// </summary>
  236. /// <param name="other">The other array to compare against.</param>
  237. /// <returns>
  238. /// <see langword="true"/> if the sizes and contents of the arrays are equal,
  239. /// <see langword="false"/> otherwise.
  240. /// </returns>
  241. public bool RecursiveEqual(Array other)
  242. {
  243. var self = (godot_array)NativeValue;
  244. var otherVariant = (godot_array)other.NativeValue;
  245. return NativeFuncs.godotsharp_array_recursive_equal(ref self, otherVariant).ToBool();
  246. }
  247. /// <summary>
  248. /// Resizes the array to contain a different number of elements. If the array
  249. /// size is smaller, elements are cleared, if bigger, new elements are
  250. /// <see langword="null"/>.
  251. /// </summary>
  252. /// <exception cref="InvalidOperationException">
  253. /// The array is read-only.
  254. /// </exception>
  255. /// <param name="newSize">The new size of the array.</param>
  256. /// <returns><see cref="Error.Ok"/> if successful, or an error code.</returns>
  257. public Error Resize(int newSize)
  258. {
  259. ThrowIfReadOnly();
  260. var self = (godot_array)NativeValue;
  261. return NativeFuncs.godotsharp_array_resize(ref self, newSize);
  262. }
  263. /// <summary>
  264. /// Reverses the order of the elements in the array.
  265. /// </summary>
  266. /// <exception cref="InvalidOperationException">
  267. /// The array is read-only.
  268. /// </exception>
  269. public void Reverse()
  270. {
  271. ThrowIfReadOnly();
  272. var self = (godot_array)NativeValue;
  273. NativeFuncs.godotsharp_array_reverse(ref self);
  274. }
  275. /// <summary>
  276. /// Shuffles the array such that the items will have a random order.
  277. /// This method uses the global random number generator common to methods
  278. /// such as <see cref="GD.Randi"/>. Call <see cref="GD.Randomize"/> to
  279. /// ensure that a new seed will be used each time if you want
  280. /// non-reproducible shuffling.
  281. /// </summary>
  282. /// <exception cref="InvalidOperationException">
  283. /// The array is read-only.
  284. /// </exception>
  285. public void Shuffle()
  286. {
  287. ThrowIfReadOnly();
  288. var self = (godot_array)NativeValue;
  289. NativeFuncs.godotsharp_array_shuffle(ref self);
  290. }
  291. /// <summary>
  292. /// Creates a shallow copy of a range of elements in the source <see cref="Array"/>.
  293. /// </summary>
  294. /// <exception cref="ArgumentOutOfRangeException">
  295. /// <paramref name="start"/> is less than 0 or greater than the array's size.
  296. /// </exception>
  297. /// <param name="start">The zero-based index at which the range starts.</param>
  298. /// <returns>A new array that contains the elements inside the slice range.</returns>
  299. public Array Slice(int start)
  300. {
  301. if (start < 0 || start > Count)
  302. throw new ArgumentOutOfRangeException(nameof(start));
  303. return GetSliceRange(start, Count, step: 1, deep: false);
  304. }
  305. /// <summary>
  306. /// Creates a shallow copy of a range of elements in the source <see cref="Array"/>.
  307. /// </summary>
  308. /// <exception cref="ArgumentOutOfRangeException">
  309. /// <paramref name="start"/> is less than 0 or greater than the array's size.
  310. /// -or-
  311. /// <paramref name="length"/> is less than 0 or greater than the array's size.
  312. /// </exception>
  313. /// <param name="start">The zero-based index at which the range starts.</param>
  314. /// <param name="length">The length of the range.</param>
  315. /// <returns>A new array that contains the elements inside the slice range.</returns>
  316. // The Slice method must have this signature to get implicit Range support.
  317. public Array Slice(int start, int length)
  318. {
  319. if (start < 0 || start > Count)
  320. throw new ArgumentOutOfRangeException(nameof(start));
  321. if (length < 0 || length > Count)
  322. throw new ArgumentOutOfRangeException(nameof(start));
  323. return GetSliceRange(start, start + length, step: 1, deep: false);
  324. }
  325. /// <summary>
  326. /// Returns the slice of the <see cref="Array"/>, from <paramref name="start"/>
  327. /// (inclusive) to <paramref name="end"/> (exclusive), as a new <see cref="Array"/>.
  328. /// The absolute value of <paramref name="start"/> and <paramref name="end"/>
  329. /// will be clamped to the array size.
  330. /// If either <paramref name="start"/> or <paramref name="end"/> are negative, they
  331. /// will be relative to the end of the array (i.e. <c>arr.GetSliceRange(0, -2)</c>
  332. /// is a shorthand for <c>arr.GetSliceRange(0, arr.Count - 2)</c>).
  333. /// If specified, <paramref name="step"/> is the relative index between source
  334. /// elements. It can be negative, then <paramref name="start"/> must be higher than
  335. /// <paramref name="end"/>. For example, <c>[0, 1, 2, 3, 4, 5].GetSliceRange(5, 1, -2)</c>
  336. /// returns <c>[5, 3]</c>.
  337. /// If <paramref name="deep"/> is true, each element will be copied by value
  338. /// rather than by reference.
  339. /// </summary>
  340. /// <param name="start">The zero-based index at which the range starts.</param>
  341. /// <param name="end">The zero-based index at which the range ends.</param>
  342. /// <param name="step">The relative index between source elements to take.</param>
  343. /// <param name="deep">If <see langword="true"/>, performs a deep copy.</param>
  344. /// <returns>A new array that contains the elements inside the slice range.</returns>
  345. public Array GetSliceRange(int start, int end, int step = 1, bool deep = false)
  346. {
  347. godot_array newArray;
  348. var self = (godot_array)NativeValue;
  349. NativeFuncs.godotsharp_array_slice(ref self, start, end, step, deep.ToGodotBool(), out newArray);
  350. return CreateTakingOwnershipOfDisposableValue(newArray);
  351. }
  352. /// <summary>
  353. /// Sorts the array.
  354. /// Note: The sorting algorithm used is not stable. This means that values
  355. /// considered equal may have their order changed when using <see cref="Sort"/>.
  356. /// Note: Strings are sorted in alphabetical order (as opposed to natural order).
  357. /// This may lead to unexpected behavior when sorting an array of strings ending
  358. /// with a sequence of numbers.
  359. /// To sort with a custom predicate use
  360. /// <see cref="Enumerable.OrderBy{TSource, TKey}(IEnumerable{TSource}, Func{TSource, TKey})"/>.
  361. /// </summary>
  362. /// <example>
  363. /// <code>
  364. /// var strings = new Godot.Collections.Array { "string1", "string2", "string10", "string11" };
  365. /// strings.Sort();
  366. /// GD.Print(strings); // Prints [string1, string10, string11, string2]
  367. /// </code>
  368. /// </example>
  369. /// <exception cref="InvalidOperationException">
  370. /// The array is read-only.
  371. /// </exception>
  372. public void Sort()
  373. {
  374. ThrowIfReadOnly();
  375. var self = (godot_array)NativeValue;
  376. NativeFuncs.godotsharp_array_sort(ref self);
  377. }
  378. /// <summary>
  379. /// Concatenates two <see cref="Array"/>s together, with the <paramref name="right"/>
  380. /// being added to the end of the <see cref="Array"/> specified in <paramref name="left"/>.
  381. /// For example, <c>[1, 2] + [3, 4]</c> results in <c>[1, 2, 3, 4]</c>.
  382. /// </summary>
  383. /// <param name="left">The first array.</param>
  384. /// <param name="right">The second array.</param>
  385. /// <returns>A new Godot Array with the contents of both arrays.</returns>
  386. public static Array operator +(Array left, Array right)
  387. {
  388. if (left == null)
  389. {
  390. if (right == null)
  391. return new Array();
  392. return right.Duplicate(deep: false);
  393. }
  394. if (right == null)
  395. return left.Duplicate(deep: false);
  396. int leftCount = left.Count;
  397. int rightCount = right.Count;
  398. Array newArray = left.Duplicate(deep: false);
  399. newArray.Resize(leftCount + rightCount);
  400. for (int i = 0; i < rightCount; i++)
  401. newArray[i + leftCount] = right[i];
  402. return newArray;
  403. }
  404. /// <summary>
  405. /// Returns the item at the given <paramref name="index"/>.
  406. /// </summary>
  407. /// <exception cref="InvalidOperationException">
  408. /// The property is assigned and the array is read-only.
  409. /// </exception>
  410. /// <exception cref="ArgumentOutOfRangeException">
  411. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  412. /// </exception>
  413. /// <value>The <see cref="Variant"/> item at the given <paramref name="index"/>.</value>
  414. public unsafe Variant this[int index]
  415. {
  416. get
  417. {
  418. GetVariantBorrowElementAt(index, out godot_variant borrowElem);
  419. return Variant.CreateCopyingBorrowed(borrowElem);
  420. }
  421. set
  422. {
  423. ThrowIfReadOnly();
  424. if (index < 0 || index >= Count)
  425. throw new ArgumentOutOfRangeException(nameof(index));
  426. var self = (godot_array)NativeValue;
  427. godot_variant* ptrw = NativeFuncs.godotsharp_array_ptrw(ref self);
  428. godot_variant* itemPtr = &ptrw[index];
  429. (*itemPtr).Dispose();
  430. *itemPtr = value.CopyNativeVariant();
  431. }
  432. }
  433. /// <summary>
  434. /// Adds an item to the end of this <see cref="Array"/>.
  435. /// This is the same as <c>append</c> or <c>push_back</c> in GDScript.
  436. /// </summary>
  437. /// <exception cref="InvalidOperationException">
  438. /// The array is read-only.
  439. /// </exception>
  440. /// <param name="item">The <see cref="Variant"/> item to add.</param>
  441. public void Add(Variant item)
  442. {
  443. ThrowIfReadOnly();
  444. godot_variant variantValue = (godot_variant)item.NativeVar;
  445. var self = (godot_array)NativeValue;
  446. _ = NativeFuncs.godotsharp_array_add(ref self, variantValue);
  447. }
  448. /// <summary>
  449. /// Adds the elements of the specified collection to the end of this <see cref="Array"/>.
  450. /// </summary>
  451. /// <exception cref="InvalidOperationException">
  452. /// The array is read-only.
  453. /// </exception>
  454. /// <exception cref="ArgumentNullException">
  455. /// The <paramref name="collection"/> is <see langword="null"/>.
  456. /// </exception>
  457. /// <param name="collection">Collection of <see cref="Variant"/> items to add.</param>
  458. public void AddRange<[MustBeVariant] T>(IEnumerable<T> collection)
  459. {
  460. ThrowIfReadOnly();
  461. if (collection == null)
  462. throw new ArgumentNullException(nameof(collection), "Value cannot be null.");
  463. // If the collection is another Godot Array, we can add the items
  464. // with a single interop call.
  465. if (collection is Array array)
  466. {
  467. var self = (godot_array)NativeValue;
  468. var collectionNative = (godot_array)array.NativeValue;
  469. _ = NativeFuncs.godotsharp_array_add_range(ref self, collectionNative);
  470. return;
  471. }
  472. if (collection is Array<T> typedArray)
  473. {
  474. var self = (godot_array)NativeValue;
  475. var collectionNative = (godot_array)typedArray.NativeValue;
  476. _ = NativeFuncs.godotsharp_array_add_range(ref self, collectionNative);
  477. return;
  478. }
  479. // If we can retrieve the count of the collection without enumerating it
  480. // (e.g.: the collections is a List<T>), use it to resize the array once
  481. // instead of growing it as we add items.
  482. if (collection.TryGetNonEnumeratedCount(out int count))
  483. {
  484. int oldCount = Count;
  485. Resize(Count + count);
  486. using var enumerator = collection.GetEnumerator();
  487. for (int i = 0; i < count; i++)
  488. {
  489. enumerator.MoveNext();
  490. this[oldCount + i] = Variant.From(enumerator.Current);
  491. }
  492. return;
  493. }
  494. foreach (var item in collection)
  495. {
  496. Add(Variant.From(item));
  497. }
  498. }
  499. /// <summary>
  500. /// Finds the index of an existing value using binary search.
  501. /// If the value is not present in the array, it returns the bitwise
  502. /// complement of the insertion index that maintains sorting order.
  503. /// Note: Calling <see cref="BinarySearch(int, int, Variant)"/> on an
  504. /// unsorted array results in unexpected behavior.
  505. /// </summary>
  506. /// <exception cref="ArgumentOutOfRangeException">
  507. /// <paramref name="index"/> is less than 0.
  508. /// -or-
  509. /// <paramref name="count"/> is less than 0.
  510. /// </exception>
  511. /// <exception cref="ArgumentException">
  512. /// <paramref name="index"/> and <paramref name="count"/> do not denote
  513. /// a valid range in the <see cref="Array"/>.
  514. /// </exception>
  515. /// <param name="index">The starting index of the range to search.</param>
  516. /// <param name="count">The length of the range to search.</param>
  517. /// <param name="item">The object to locate.</param>
  518. /// <returns>
  519. /// The index of the item in the array, if <paramref name="item"/> is found;
  520. /// otherwise, a negative number that is the bitwise complement of the index
  521. /// of the next element that is larger than <paramref name="item"/> or, if
  522. /// there is no larger element, the bitwise complement of <see cref="Count"/>.
  523. /// </returns>
  524. public int BinarySearch(int index, int count, Variant item)
  525. {
  526. if (index < 0)
  527. throw new ArgumentOutOfRangeException(nameof(index), "index cannot be negative.");
  528. if (count < 0)
  529. throw new ArgumentOutOfRangeException(nameof(count), "count cannot be negative.");
  530. if (Count - index < count)
  531. throw new ArgumentException("length is out of bounds or count is greater than the number of elements.");
  532. if (Count == 0)
  533. {
  534. // Special case for empty array to avoid an interop call.
  535. return -1;
  536. }
  537. godot_variant variantValue = (godot_variant)item.NativeVar;
  538. var self = (godot_array)NativeValue;
  539. return NativeFuncs.godotsharp_array_binary_search(ref self, index, count, variantValue);
  540. }
  541. /// <summary>
  542. /// Finds the index of an existing value using binary search.
  543. /// If the value is not present in the array, it returns the bitwise
  544. /// complement of the insertion index that maintains sorting order.
  545. /// Note: Calling <see cref="BinarySearch(Variant)"/> on an unsorted
  546. /// array results in unexpected behavior.
  547. /// </summary>
  548. /// <param name="item">The object to locate.</param>
  549. /// <returns>
  550. /// The index of the item in the array, if <paramref name="item"/> is found;
  551. /// otherwise, a negative number that is the bitwise complement of the index
  552. /// of the next element that is larger than <paramref name="item"/> or, if
  553. /// there is no larger element, the bitwise complement of <see cref="Count"/>.
  554. /// </returns>
  555. public int BinarySearch(Variant item)
  556. {
  557. return BinarySearch(0, Count, item);
  558. }
  559. /// <summary>
  560. /// Returns <see langword="true"/> if the array contains the given value.
  561. /// </summary>
  562. /// <example>
  563. /// <code>
  564. /// var arr = new Godot.Collections.Array { "inside", 7 };
  565. /// GD.Print(arr.Contains("inside")); // True
  566. /// GD.Print(arr.Contains("outside")); // False
  567. /// GD.Print(arr.Contains(7)); // True
  568. /// GD.Print(arr.Contains("7")); // False
  569. /// </code>
  570. /// </example>
  571. /// <param name="item">The <see cref="Variant"/> item to look for.</param>
  572. /// <returns>Whether or not this array contains the given item.</returns>
  573. public bool Contains(Variant item) => IndexOf(item) != -1;
  574. /// <summary>
  575. /// Clears the array. This is the equivalent to using <see cref="Resize(int)"/>
  576. /// with a size of <c>0</c>
  577. /// </summary>
  578. /// <exception cref="InvalidOperationException">
  579. /// The array is read-only.
  580. /// </exception>
  581. public void Clear() => Resize(0);
  582. /// <summary>
  583. /// Searches the array for a value and returns its index or <c>-1</c> if not found.
  584. /// </summary>
  585. /// <param name="item">The <see cref="Variant"/> item to search for.</param>
  586. /// <returns>The index of the item, or -1 if not found.</returns>
  587. public int IndexOf(Variant item)
  588. {
  589. if (Count == 0)
  590. {
  591. // Special case for empty array to avoid an interop call.
  592. return -1;
  593. }
  594. godot_variant variantValue = (godot_variant)item.NativeVar;
  595. var self = (godot_array)NativeValue;
  596. return NativeFuncs.godotsharp_array_index_of(ref self, variantValue);
  597. }
  598. /// <summary>
  599. /// Searches the array for a value and returns its index or <c>-1</c> if not found.
  600. /// </summary>
  601. /// <exception cref="ArgumentOutOfRangeException">
  602. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  603. /// </exception>
  604. /// <param name="item">The <see cref="Variant"/> item to search for.</param>
  605. /// <param name="index">The initial search index to start from.</param>
  606. /// <returns>The index of the item, or -1 if not found.</returns>
  607. public int IndexOf(Variant item, int index)
  608. {
  609. if (index < 0 || index > Count)
  610. throw new ArgumentOutOfRangeException(nameof(index));
  611. if (Count == 0)
  612. {
  613. // Special case for empty array to avoid an interop call.
  614. return -1;
  615. }
  616. godot_variant variantValue = (godot_variant)item.NativeVar;
  617. var self = (godot_array)NativeValue;
  618. return NativeFuncs.godotsharp_array_index_of(ref self, variantValue, index);
  619. }
  620. /// <summary>
  621. /// Searches the array for a value in reverse order and returns its index
  622. /// or <c>-1</c> if not found.
  623. /// </summary>
  624. /// <param name="item">The <see cref="Variant"/> item to search for.</param>
  625. /// <returns>The index of the item, or -1 if not found.</returns>
  626. public int LastIndexOf(Variant item)
  627. {
  628. if (Count == 0)
  629. {
  630. // Special case for empty array to avoid an interop call.
  631. return -1;
  632. }
  633. godot_variant variantValue = (godot_variant)item.NativeVar;
  634. var self = (godot_array)NativeValue;
  635. return NativeFuncs.godotsharp_array_last_index_of(ref self, variantValue, Count - 1);
  636. }
  637. /// <summary>
  638. /// Searches the array for a value in reverse order and returns its index
  639. /// or <c>-1</c> if not found.
  640. /// </summary>
  641. /// <exception cref="ArgumentOutOfRangeException">
  642. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  643. /// </exception>
  644. /// <param name="item">The <see cref="Variant"/> item to search for.</param>
  645. /// <param name="index">The initial search index to start from.</param>
  646. /// <returns>The index of the item, or -1 if not found.</returns>
  647. public int LastIndexOf(Variant item, int index)
  648. {
  649. if (index < 0 || index >= Count)
  650. throw new ArgumentOutOfRangeException(nameof(index));
  651. if (Count == 0)
  652. {
  653. // Special case for empty array to avoid an interop call.
  654. return -1;
  655. }
  656. godot_variant variantValue = (godot_variant)item.NativeVar;
  657. var self = (godot_array)NativeValue;
  658. return NativeFuncs.godotsharp_array_last_index_of(ref self, variantValue, index);
  659. }
  660. /// <summary>
  661. /// Inserts a new element at a given position in the array. The position
  662. /// must be valid, or at the end of the array (<c>pos == Count - 1</c>).
  663. /// Existing items will be moved to the right.
  664. /// </summary>
  665. /// <exception cref="InvalidOperationException">
  666. /// The array is read-only.
  667. /// </exception>
  668. /// <exception cref="ArgumentOutOfRangeException">
  669. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  670. /// </exception>
  671. /// <param name="index">The index to insert at.</param>
  672. /// <param name="item">The <see cref="Variant"/> item to insert.</param>
  673. public void Insert(int index, Variant item)
  674. {
  675. ThrowIfReadOnly();
  676. if (index < 0 || index > Count)
  677. throw new ArgumentOutOfRangeException(nameof(index));
  678. godot_variant variantValue = (godot_variant)item.NativeVar;
  679. var self = (godot_array)NativeValue;
  680. NativeFuncs.godotsharp_array_insert(ref self, index, variantValue);
  681. }
  682. /// <summary>
  683. /// Removes the first occurrence of the specified <paramref name="item"/>
  684. /// from this <see cref="Array"/>.
  685. /// </summary>
  686. /// <exception cref="InvalidOperationException">
  687. /// The array is read-only.
  688. /// </exception>
  689. /// <param name="item">The value to remove.</param>
  690. public bool Remove(Variant item)
  691. {
  692. ThrowIfReadOnly();
  693. int index = IndexOf(item);
  694. if (index >= 0)
  695. {
  696. RemoveAt(index);
  697. return true;
  698. }
  699. return false;
  700. }
  701. /// <summary>
  702. /// Removes an element from the array by index.
  703. /// To remove an element by searching for its value, use
  704. /// <see cref="Remove(Variant)"/> instead.
  705. /// </summary>
  706. /// <exception cref="InvalidOperationException">
  707. /// The array is read-only.
  708. /// </exception>
  709. /// <exception cref="ArgumentOutOfRangeException">
  710. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  711. /// </exception>
  712. /// <param name="index">The index of the element to remove.</param>
  713. public void RemoveAt(int index)
  714. {
  715. ThrowIfReadOnly();
  716. if (index < 0 || index > Count)
  717. throw new ArgumentOutOfRangeException(nameof(index));
  718. var self = (godot_array)NativeValue;
  719. NativeFuncs.godotsharp_array_remove_at(ref self, index);
  720. }
  721. // ICollection
  722. /// <summary>
  723. /// Returns the number of elements in this <see cref="Array"/>.
  724. /// This is also known as the size or length of the array.
  725. /// </summary>
  726. /// <returns>The number of elements.</returns>
  727. public int Count => NativeValue.DangerousSelfRef.Size;
  728. bool ICollection.IsSynchronized => false;
  729. object ICollection.SyncRoot => false;
  730. /// <summary>
  731. /// Returns <see langword="true"/> if the array is read-only.
  732. /// See <see cref="MakeReadOnly"/>.
  733. /// </summary>
  734. public bool IsReadOnly => NativeValue.DangerousSelfRef.IsReadOnly;
  735. /// <summary>
  736. /// Makes the <see cref="Array"/> read-only, i.e. disabled modying of the
  737. /// array's elements. Does not apply to nested content, e.g. content of
  738. /// nested arrays.
  739. /// </summary>
  740. public void MakeReadOnly()
  741. {
  742. if (IsReadOnly)
  743. {
  744. // Avoid interop call when the array is already read-only.
  745. return;
  746. }
  747. var self = (godot_array)NativeValue;
  748. NativeFuncs.godotsharp_array_make_read_only(ref self);
  749. }
  750. /// <summary>
  751. /// Copies the elements of this <see cref="Array"/> to the given
  752. /// <see cref="Variant"/> C# array, starting at the given index.
  753. /// </summary>
  754. /// <exception cref="ArgumentOutOfRangeException">
  755. /// <paramref name="arrayIndex"/> is less than 0 or greater than the array's size.
  756. /// </exception>
  757. /// <param name="array">The array to copy to.</param>
  758. /// <param name="arrayIndex">The index to start at.</param>
  759. public void CopyTo(Variant[] array, int arrayIndex)
  760. {
  761. if (array == null)
  762. throw new ArgumentNullException(nameof(array), "Value cannot be null.");
  763. if (arrayIndex < 0)
  764. {
  765. throw new ArgumentOutOfRangeException(nameof(arrayIndex),
  766. "Number was less than the array's lower bound in the first dimension.");
  767. }
  768. int count = Count;
  769. if (array.Length < (arrayIndex + count))
  770. {
  771. throw new ArgumentException(
  772. "Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
  773. }
  774. unsafe
  775. {
  776. for (int i = 0; i < count; i++)
  777. {
  778. array[arrayIndex] = Variant.CreateCopyingBorrowed(NativeValue.DangerousSelfRef.Elements[i]);
  779. arrayIndex++;
  780. }
  781. }
  782. }
  783. void ICollection.CopyTo(System.Array array, int index)
  784. {
  785. if (array == null)
  786. throw new ArgumentNullException(nameof(array), "Value cannot be null.");
  787. if (index < 0)
  788. {
  789. throw new ArgumentOutOfRangeException(nameof(index),
  790. "Number was less than the array's lower bound in the first dimension.");
  791. }
  792. int count = Count;
  793. if (array.Length < (index + count))
  794. {
  795. throw new ArgumentException(
  796. "Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
  797. }
  798. unsafe
  799. {
  800. for (int i = 0; i < count; i++)
  801. {
  802. object boxedVariant = Variant.CreateCopyingBorrowed(NativeValue.DangerousSelfRef.Elements[i]);
  803. array.SetValue(boxedVariant, index);
  804. index++;
  805. }
  806. }
  807. }
  808. // IEnumerable
  809. /// <summary>
  810. /// Gets an enumerator for this <see cref="Array"/>.
  811. /// </summary>
  812. /// <returns>An enumerator.</returns>
  813. public IEnumerator<Variant> GetEnumerator()
  814. {
  815. int count = Count;
  816. for (int i = 0; i < count; i++)
  817. {
  818. yield return this[i];
  819. }
  820. }
  821. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  822. /// <summary>
  823. /// Converts this <see cref="Array"/> to a string.
  824. /// </summary>
  825. /// <returns>A string representation of this array.</returns>
  826. public override string ToString()
  827. {
  828. var self = (godot_array)NativeValue;
  829. NativeFuncs.godotsharp_array_to_string(ref self, out godot_string str);
  830. using (str)
  831. return Marshaling.ConvertStringToManaged(str);
  832. }
  833. /// <summary>
  834. /// The variant returned via the <paramref name="elem"/> parameter is owned by the Array and must not be disposed.
  835. /// </summary>
  836. /// <exception cref="ArgumentOutOfRangeException">
  837. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  838. /// </exception>
  839. internal void GetVariantBorrowElementAt(int index, out godot_variant elem)
  840. {
  841. if (index < 0 || index >= Count)
  842. throw new ArgumentOutOfRangeException(nameof(index));
  843. GetVariantBorrowElementAtUnchecked(index, out elem);
  844. }
  845. /// <summary>
  846. /// The variant returned via the <paramref name="elem"/> parameter is owned by the Array and must not be disposed.
  847. /// </summary>
  848. internal unsafe void GetVariantBorrowElementAtUnchecked(int index, out godot_variant elem)
  849. {
  850. elem = NativeValue.DangerousSelfRef.Elements[index];
  851. }
  852. private void ThrowIfReadOnly()
  853. {
  854. if (IsReadOnly)
  855. {
  856. throw new InvalidOperationException("Array instance is read-only.");
  857. }
  858. }
  859. }
  860. internal interface IGenericGodotArray
  861. {
  862. public Array UnderlyingArray { get; }
  863. }
  864. /// <summary>
  865. /// Typed wrapper around Godot's Array class, an array of Variant
  866. /// typed elements allocated in the engine in C++. Useful when
  867. /// interfacing with the engine. Otherwise prefer .NET collections
  868. /// such as arrays or <see cref="List{T}"/>.
  869. /// </summary>
  870. /// <typeparam name="T">The type of the array.</typeparam>
  871. [SuppressMessage("ReSharper", "RedundantExtendsListEntry")]
  872. [SuppressMessage("Naming", "CA1710", MessageId = "Identifiers should have correct suffix")]
  873. public sealed class Array<[MustBeVariant] T> :
  874. IList<T>,
  875. IReadOnlyList<T>,
  876. ICollection<T>,
  877. IEnumerable<T>,
  878. IGenericGodotArray
  879. {
  880. private static godot_variant ToVariantFunc(in Array<T> godotArray) =>
  881. VariantUtils.CreateFromArray(godotArray);
  882. private static Array<T> FromVariantFunc(in godot_variant variant) =>
  883. VariantUtils.ConvertToArray<T>(variant);
  884. static unsafe Array()
  885. {
  886. VariantUtils.GenericConversion<Array<T>>.ToVariantCb = &ToVariantFunc;
  887. VariantUtils.GenericConversion<Array<T>>.FromVariantCb = &FromVariantFunc;
  888. }
  889. private readonly Array _underlyingArray;
  890. Array IGenericGodotArray.UnderlyingArray => _underlyingArray;
  891. internal ref godot_array.movable NativeValue
  892. {
  893. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  894. get => ref _underlyingArray.NativeValue;
  895. }
  896. /// <summary>
  897. /// Constructs a new empty <see cref="Array{T}"/>.
  898. /// </summary>
  899. public Array()
  900. {
  901. _underlyingArray = new Array();
  902. }
  903. /// <summary>
  904. /// Constructs a new <see cref="Array{T}"/> from the given collection's elements.
  905. /// </summary>
  906. /// <param name="collection">The collection of elements to construct from.</param>
  907. /// <returns>A new Godot Array.</returns>
  908. public Array(IEnumerable<T> collection)
  909. {
  910. if (collection == null)
  911. throw new ArgumentNullException(nameof(collection));
  912. _underlyingArray = new Array();
  913. foreach (T element in collection)
  914. Add(element);
  915. }
  916. /// <summary>
  917. /// Constructs a new <see cref="Array{T}"/> from the given items.
  918. /// </summary>
  919. /// <param name="array">The items to put in the new array.</param>
  920. /// <returns>A new Godot Array.</returns>
  921. public Array(T[] array) : this()
  922. {
  923. if (array == null)
  924. throw new ArgumentNullException(nameof(array));
  925. _underlyingArray = new Array();
  926. foreach (T element in array)
  927. Add(element);
  928. }
  929. /// <summary>
  930. /// Constructs a typed <see cref="Array{T}"/> from an untyped <see cref="Array"/>.
  931. /// </summary>
  932. /// <param name="array">The untyped array to construct from.</param>
  933. public Array(Array array)
  934. {
  935. _underlyingArray = array;
  936. }
  937. // Explicit name to make it very clear
  938. internal static Array<T> CreateTakingOwnershipOfDisposableValue(godot_array nativeValueToOwn)
  939. => new Array<T>(Array.CreateTakingOwnershipOfDisposableValue(nativeValueToOwn));
  940. /// <summary>
  941. /// Converts this typed <see cref="Array{T}"/> to an untyped <see cref="Array"/>.
  942. /// </summary>
  943. /// <param name="from">The typed array to convert.</param>
  944. public static explicit operator Array(Array<T> from)
  945. {
  946. return from?._underlyingArray;
  947. }
  948. /// <summary>
  949. /// Duplicates this <see cref="Array{T}"/>.
  950. /// </summary>
  951. /// <param name="deep">If <see langword="true"/>, performs a deep copy.</param>
  952. /// <returns>A new Godot Array.</returns>
  953. public Array<T> Duplicate(bool deep = false)
  954. {
  955. return new Array<T>(_underlyingArray.Duplicate(deep));
  956. }
  957. /// <summary>
  958. /// Assigns the given value to all elements in the array. This can typically be
  959. /// used together with <see cref="Resize(int)"/> to create an array with a given
  960. /// size and initialized elements.
  961. /// Note: If <paramref name="value"/> is of a reference type (<see cref="GodotObject"/>
  962. /// derived, <see cref="Array"/> or <see cref="Dictionary"/>, etc.) then the array
  963. /// is filled with the references to the same object, i.e. no duplicates are
  964. /// created.
  965. /// </summary>
  966. /// <example>
  967. /// <code>
  968. /// var array = new Godot.Collections.Array&lt;int&gt;();
  969. /// array.Resize(10);
  970. /// array.Fill(0); // Initialize the 10 elements to 0.
  971. /// </code>
  972. /// </example>
  973. /// <exception cref="InvalidOperationException">
  974. /// The array is read-only.
  975. /// </exception>
  976. /// <param name="value">The value to fill the array with.</param>
  977. public void Fill(T value)
  978. {
  979. ThrowIfReadOnly();
  980. godot_variant variantValue = VariantUtils.CreateFrom(value);
  981. var self = (godot_array)_underlyingArray.NativeValue;
  982. NativeFuncs.godotsharp_array_fill(ref self, variantValue);
  983. }
  984. /// <summary>
  985. /// Returns the maximum value contained in the array if all elements are of
  986. /// comparable types. If the elements can't be compared, <see langword="default"/>
  987. /// is returned.
  988. /// </summary>
  989. /// <returns>The maximum value contained in the array.</returns>
  990. public T Max()
  991. {
  992. godot_variant resVariant;
  993. var self = (godot_array)_underlyingArray.NativeValue;
  994. NativeFuncs.godotsharp_array_max(ref self, out resVariant);
  995. return VariantUtils.ConvertTo<T>(resVariant);
  996. }
  997. /// <summary>
  998. /// Returns the minimum value contained in the array if all elements are of
  999. /// comparable types. If the elements can't be compared, <see langword="default"/>
  1000. /// is returned.
  1001. /// </summary>
  1002. /// <returns>The minimum value contained in the array.</returns>
  1003. public T Min()
  1004. {
  1005. godot_variant resVariant;
  1006. var self = (godot_array)_underlyingArray.NativeValue;
  1007. NativeFuncs.godotsharp_array_min(ref self, out resVariant);
  1008. return VariantUtils.ConvertTo<T>(resVariant);
  1009. }
  1010. /// <summary>
  1011. /// Returns a random value from the target array.
  1012. /// </summary>
  1013. /// <example>
  1014. /// <code>
  1015. /// var array = new Godot.Collections.Array&lt;int&gt; { 1, 2, 3, 4 };
  1016. /// GD.Print(array.PickRandom()); // Prints either of the four numbers.
  1017. /// </code>
  1018. /// </example>
  1019. /// <returns>A random element from the array.</returns>
  1020. public T PickRandom()
  1021. {
  1022. godot_variant resVariant;
  1023. var self = (godot_array)_underlyingArray.NativeValue;
  1024. NativeFuncs.godotsharp_array_pick_random(ref self, out resVariant);
  1025. return VariantUtils.ConvertTo<T>(resVariant);
  1026. }
  1027. /// <summary>
  1028. /// Compares this <see cref="Array{T}"/> against the <paramref name="other"/>
  1029. /// <see cref="Array{T}"/> recursively. Returns <see langword="true"/> if the
  1030. /// sizes and contents of the arrays are equal, <see langword="false"/>
  1031. /// otherwise.
  1032. /// </summary>
  1033. /// <param name="other">The other array to compare against.</param>
  1034. /// <returns>
  1035. /// <see langword="true"/> if the sizes and contents of the arrays are equal,
  1036. /// <see langword="false"/> otherwise.
  1037. /// </returns>
  1038. public bool RecursiveEqual(Array<T> other)
  1039. {
  1040. return _underlyingArray.RecursiveEqual(other._underlyingArray);
  1041. }
  1042. /// <summary>
  1043. /// Resizes this <see cref="Array{T}"/> to the given size.
  1044. /// </summary>
  1045. /// <exception cref="InvalidOperationException">
  1046. /// The array is read-only.
  1047. /// </exception>
  1048. /// <param name="newSize">The new size of the array.</param>
  1049. /// <returns><see cref="Error.Ok"/> if successful, or an error code.</returns>
  1050. public Error Resize(int newSize)
  1051. {
  1052. return _underlyingArray.Resize(newSize);
  1053. }
  1054. /// <summary>
  1055. /// Reverses the order of the elements in the array.
  1056. /// </summary>
  1057. /// <exception cref="InvalidOperationException">
  1058. /// The array is read-only.
  1059. /// </exception>
  1060. public void Reverse()
  1061. {
  1062. _underlyingArray.Reverse();
  1063. }
  1064. /// <summary>
  1065. /// Shuffles the array such that the items will have a random order.
  1066. /// This method uses the global random number generator common to methods
  1067. /// such as <see cref="GD.Randi"/>. Call <see cref="GD.Randomize"/> to
  1068. /// ensure that a new seed will be used each time if you want
  1069. /// non-reproducible shuffling.
  1070. /// </summary>
  1071. /// <exception cref="InvalidOperationException">
  1072. /// The array is read-only.
  1073. /// </exception>
  1074. public void Shuffle()
  1075. {
  1076. _underlyingArray.Shuffle();
  1077. }
  1078. /// <summary>
  1079. /// Creates a shallow copy of a range of elements in the source <see cref="Array{T}"/>.
  1080. /// </summary>
  1081. /// <exception cref="ArgumentOutOfRangeException">
  1082. /// <paramref name="start"/> is less than 0 or greater than the array's size.
  1083. /// </exception>
  1084. /// <param name="start">The zero-based index at which the range starts.</param>
  1085. /// <returns>A new array that contains the elements inside the slice range.</returns>
  1086. public Array<T> Slice(int start)
  1087. {
  1088. return GetSliceRange(start, Count, step: 1, deep: false);
  1089. }
  1090. /// <summary>
  1091. /// Creates a shallow copy of a range of elements in the source <see cref="Array{T}"/>.
  1092. /// </summary>
  1093. /// <exception cref="ArgumentOutOfRangeException">
  1094. /// <paramref name="start"/> is less than 0 or greater than the array's size.
  1095. /// -or-
  1096. /// <paramref name="length"/> is less than 0 or greater than the array's size.
  1097. /// </exception>
  1098. /// <param name="start">The zero-based index at which the range starts.</param>
  1099. /// <param name="length">The length of the range.</param>
  1100. /// <returns>A new array that contains the elements inside the slice range.</returns>
  1101. // The Slice method must have this signature to get implicit Range support.
  1102. public Array<T> Slice(int start, int length)
  1103. {
  1104. return GetSliceRange(start, start + length, step: 1, deep: false);
  1105. }
  1106. /// <summary>
  1107. /// Returns the slice of the <see cref="Array{T}"/>, from <paramref name="start"/>
  1108. /// (inclusive) to <paramref name="end"/> (exclusive), as a new <see cref="Array{T}"/>.
  1109. /// The absolute value of <paramref name="start"/> and <paramref name="end"/>
  1110. /// will be clamped to the array size.
  1111. /// If either <paramref name="start"/> or <paramref name="end"/> are negative, they
  1112. /// will be relative to the end of the array (i.e. <c>arr.GetSliceRange(0, -2)</c>
  1113. /// is a shorthand for <c>arr.GetSliceRange(0, arr.Count - 2)</c>).
  1114. /// If specified, <paramref name="step"/> is the relative index between source
  1115. /// elements. It can be negative, then <paramref name="start"/> must be higher than
  1116. /// <paramref name="end"/>. For example, <c>[0, 1, 2, 3, 4, 5].GetSliceRange(5, 1, -2)</c>
  1117. /// returns <c>[5, 3]</c>.
  1118. /// If <paramref name="deep"/> is true, each element will be copied by value
  1119. /// rather than by reference.
  1120. /// </summary>
  1121. /// <param name="start">The zero-based index at which the range starts.</param>
  1122. /// <param name="end">The zero-based index at which the range ends.</param>
  1123. /// <param name="step">The relative index between source elements to take.</param>
  1124. /// <param name="deep">If <see langword="true"/>, performs a deep copy.</param>
  1125. /// <returns>A new array that contains the elements inside the slice range.</returns>
  1126. public Array<T> GetSliceRange(int start, int end, int step = 1, bool deep = false)
  1127. {
  1128. return new Array<T>(_underlyingArray.GetSliceRange(start, end, step, deep));
  1129. }
  1130. /// <summary>
  1131. /// Sorts the array.
  1132. /// Note: The sorting algorithm used is not stable. This means that values
  1133. /// considered equal may have their order changed when using <see cref="Sort"/>.
  1134. /// Note: Strings are sorted in alphabetical order (as opposed to natural order).
  1135. /// This may lead to unexpected behavior when sorting an array of strings ending
  1136. /// with a sequence of numbers.
  1137. /// To sort with a custom predicate use
  1138. /// <see cref="Enumerable.OrderBy{TSource, TKey}(IEnumerable{TSource}, Func{TSource, TKey})"/>.
  1139. /// </summary>
  1140. /// <example>
  1141. /// <code>
  1142. /// var strings = new Godot.Collections.Array&lt;string&gt; { "string1", "string2", "string10", "string11" };
  1143. /// strings.Sort();
  1144. /// GD.Print(strings); // Prints [string1, string10, string11, string2]
  1145. /// </code>
  1146. /// </example>
  1147. /// <exception cref="InvalidOperationException">
  1148. /// The array is read-only.
  1149. /// </exception>
  1150. public void Sort()
  1151. {
  1152. _underlyingArray.Sort();
  1153. }
  1154. /// <summary>
  1155. /// Concatenates two <see cref="Array{T}"/>s together, with the <paramref name="right"/>
  1156. /// being added to the end of the <see cref="Array{T}"/> specified in <paramref name="left"/>.
  1157. /// For example, <c>[1, 2] + [3, 4]</c> results in <c>[1, 2, 3, 4]</c>.
  1158. /// </summary>
  1159. /// <param name="left">The first array.</param>
  1160. /// <param name="right">The second array.</param>
  1161. /// <returns>A new Godot Array with the contents of both arrays.</returns>
  1162. public static Array<T> operator +(Array<T> left, Array<T> right)
  1163. {
  1164. if (left == null)
  1165. {
  1166. if (right == null)
  1167. return new Array<T>();
  1168. return right.Duplicate(deep: false);
  1169. }
  1170. if (right == null)
  1171. return left.Duplicate(deep: false);
  1172. return new Array<T>(left._underlyingArray + right._underlyingArray);
  1173. }
  1174. // IList<T>
  1175. /// <summary>
  1176. /// Returns the item at the given <paramref name="index"/>.
  1177. /// </summary>
  1178. /// <exception cref="InvalidOperationException">
  1179. /// The property is assigned and the array is read-only.
  1180. /// </exception>
  1181. /// <exception cref="ArgumentOutOfRangeException">
  1182. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  1183. /// </exception>
  1184. /// <value>The <see cref="Variant"/> item at the given <paramref name="index"/>.</value>
  1185. public unsafe T this[int index]
  1186. {
  1187. get
  1188. {
  1189. _underlyingArray.GetVariantBorrowElementAt(index, out godot_variant borrowElem);
  1190. return VariantUtils.ConvertTo<T>(borrowElem);
  1191. }
  1192. set
  1193. {
  1194. ThrowIfReadOnly();
  1195. if (index < 0 || index >= Count)
  1196. throw new ArgumentOutOfRangeException(nameof(index));
  1197. var self = (godot_array)_underlyingArray.NativeValue;
  1198. godot_variant* ptrw = NativeFuncs.godotsharp_array_ptrw(ref self);
  1199. godot_variant* itemPtr = &ptrw[index];
  1200. (*itemPtr).Dispose();
  1201. *itemPtr = VariantUtils.CreateFrom(value);
  1202. }
  1203. }
  1204. /// <summary>
  1205. /// Searches the array for a value and returns its index or <c>-1</c> if not found.
  1206. /// </summary>
  1207. /// <param name="item">The <see cref="Variant"/> item to search for.</param>
  1208. /// <returns>The index of the item, or -1 if not found.</returns>
  1209. public int IndexOf(T item)
  1210. {
  1211. if (Count == 0)
  1212. {
  1213. // Special case for empty array to avoid an interop call.
  1214. return -1;
  1215. }
  1216. using var variantValue = VariantUtils.CreateFrom(item);
  1217. var self = (godot_array)_underlyingArray.NativeValue;
  1218. return NativeFuncs.godotsharp_array_index_of(ref self, variantValue);
  1219. }
  1220. /// <summary>
  1221. /// Searches the array for a value and returns its index or <c>-1</c> if not found.
  1222. /// </summary>
  1223. /// <exception cref="ArgumentOutOfRangeException">
  1224. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  1225. /// </exception>
  1226. /// <param name="item">The <see cref="Variant"/> item to search for.</param>
  1227. /// <param name="index">The initial search index to start from.</param>
  1228. /// <returns>The index of the item, or -1 if not found.</returns>
  1229. public int IndexOf(T item, int index)
  1230. {
  1231. if (index < 0 || index > Count)
  1232. throw new ArgumentOutOfRangeException(nameof(index));
  1233. if (Count == 0)
  1234. {
  1235. // Special case for empty array to avoid an interop call.
  1236. return -1;
  1237. }
  1238. godot_variant variantValue = VariantUtils.CreateFrom(item);
  1239. var self = (godot_array)_underlyingArray.NativeValue;
  1240. return NativeFuncs.godotsharp_array_index_of(ref self, variantValue, index);
  1241. }
  1242. /// <summary>
  1243. /// Searches the array for a value in reverse order and returns its index
  1244. /// or <c>-1</c> if not found.
  1245. /// </summary>
  1246. /// <param name="item">The <see cref="Variant"/> item to search for.</param>
  1247. /// <returns>The index of the item, or -1 if not found.</returns>
  1248. public int LastIndexOf(Variant item)
  1249. {
  1250. if (Count == 0)
  1251. {
  1252. // Special case for empty array to avoid an interop call.
  1253. return -1;
  1254. }
  1255. godot_variant variantValue = VariantUtils.CreateFrom(item);
  1256. var self = (godot_array)_underlyingArray.NativeValue;
  1257. return NativeFuncs.godotsharp_array_last_index_of(ref self, variantValue, Count - 1);
  1258. }
  1259. /// <summary>
  1260. /// Searches the array for a value in reverse order and returns its index
  1261. /// or <c>-1</c> if not found.
  1262. /// </summary>
  1263. /// <exception cref="ArgumentOutOfRangeException">
  1264. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  1265. /// </exception>
  1266. /// <param name="item">The <see cref="Variant"/> item to search for.</param>
  1267. /// <param name="index">The initial search index to start from.</param>
  1268. /// <returns>The index of the item, or -1 if not found.</returns>
  1269. public int LastIndexOf(Variant item, int index)
  1270. {
  1271. if (index < 0 || index >= Count)
  1272. throw new ArgumentOutOfRangeException(nameof(index));
  1273. if (Count == 0)
  1274. {
  1275. // Special case for empty array to avoid an interop call.
  1276. return -1;
  1277. }
  1278. godot_variant variantValue = VariantUtils.CreateFrom(item);
  1279. var self = (godot_array)_underlyingArray.NativeValue;
  1280. return NativeFuncs.godotsharp_array_last_index_of(ref self, variantValue, index);
  1281. }
  1282. /// <summary>
  1283. /// Inserts a new element at a given position in the array. The position
  1284. /// must be valid, or at the end of the array (<c>pos == Count - 1</c>).
  1285. /// Existing items will be moved to the right.
  1286. /// </summary>
  1287. /// <exception cref="InvalidOperationException">
  1288. /// The array is read-only.
  1289. /// </exception>
  1290. /// <exception cref="ArgumentOutOfRangeException">
  1291. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  1292. /// </exception>
  1293. /// <param name="index">The index to insert at.</param>
  1294. /// <param name="item">The <see cref="Variant"/> item to insert.</param>
  1295. public void Insert(int index, T item)
  1296. {
  1297. ThrowIfReadOnly();
  1298. if (index < 0 || index > Count)
  1299. throw new ArgumentOutOfRangeException(nameof(index));
  1300. using var variantValue = VariantUtils.CreateFrom(item);
  1301. var self = (godot_array)_underlyingArray.NativeValue;
  1302. NativeFuncs.godotsharp_array_insert(ref self, index, variantValue);
  1303. }
  1304. /// <summary>
  1305. /// Removes an element from the array by index.
  1306. /// To remove an element by searching for its value, use
  1307. /// <see cref="Remove(T)"/> instead.
  1308. /// </summary>
  1309. /// <exception cref="InvalidOperationException">
  1310. /// The array is read-only.
  1311. /// </exception>
  1312. /// <exception cref="ArgumentOutOfRangeException">
  1313. /// <paramref name="index"/> is less than 0 or greater than the array's size.
  1314. /// </exception>
  1315. /// <param name="index">The index of the element to remove.</param>
  1316. public void RemoveAt(int index)
  1317. {
  1318. _underlyingArray.RemoveAt(index);
  1319. }
  1320. // ICollection<T>
  1321. /// <summary>
  1322. /// Returns the number of elements in this <see cref="Array{T}"/>.
  1323. /// This is also known as the size or length of the array.
  1324. /// </summary>
  1325. /// <returns>The number of elements.</returns>
  1326. public int Count => _underlyingArray.Count;
  1327. /// <summary>
  1328. /// Returns <see langword="true"/> if the array is read-only.
  1329. /// See <see cref="MakeReadOnly"/>.
  1330. /// </summary>
  1331. public bool IsReadOnly => _underlyingArray.IsReadOnly;
  1332. /// <summary>
  1333. /// Makes the <see cref="Array{T}"/> read-only, i.e. disabled modying of the
  1334. /// array's elements. Does not apply to nested content, e.g. content of
  1335. /// nested arrays.
  1336. /// </summary>
  1337. public void MakeReadOnly()
  1338. {
  1339. _underlyingArray.MakeReadOnly();
  1340. }
  1341. /// <summary>
  1342. /// Adds an item to the end of this <see cref="Array{T}"/>.
  1343. /// This is the same as <c>append</c> or <c>push_back</c> in GDScript.
  1344. /// </summary>
  1345. /// <exception cref="InvalidOperationException">
  1346. /// The array is read-only.
  1347. /// </exception>
  1348. /// <param name="item">The <see cref="Variant"/> item to add.</param>
  1349. public void Add(T item)
  1350. {
  1351. ThrowIfReadOnly();
  1352. using var variantValue = VariantUtils.CreateFrom(item);
  1353. var self = (godot_array)_underlyingArray.NativeValue;
  1354. _ = NativeFuncs.godotsharp_array_add(ref self, variantValue);
  1355. }
  1356. /// <summary>
  1357. /// Adds the elements of the specified collection to the end of this <see cref="Array{T}"/>.
  1358. /// </summary>
  1359. /// <exception cref="InvalidOperationException">
  1360. /// The array is read-only.
  1361. /// </exception>
  1362. /// <exception cref="ArgumentNullException">
  1363. /// The <paramref name="collection"/> is <see langword="null"/>.
  1364. /// </exception>
  1365. /// <param name="collection">Collection of <see cref="Variant"/> items to add.</param>
  1366. public void AddRange(IEnumerable<T> collection)
  1367. {
  1368. ThrowIfReadOnly();
  1369. if (collection == null)
  1370. throw new ArgumentNullException(nameof(collection), "Value cannot be null.");
  1371. // If the collection is another Godot Array, we can add the items
  1372. // with a single interop call.
  1373. if (collection is Array array)
  1374. {
  1375. var self = (godot_array)_underlyingArray.NativeValue;
  1376. var collectionNative = (godot_array)array.NativeValue;
  1377. _ = NativeFuncs.godotsharp_array_add_range(ref self, collectionNative);
  1378. return;
  1379. }
  1380. if (collection is Array<T> typedArray)
  1381. {
  1382. var self = (godot_array)_underlyingArray.NativeValue;
  1383. var collectionNative = (godot_array)typedArray._underlyingArray.NativeValue;
  1384. _ = NativeFuncs.godotsharp_array_add_range(ref self, collectionNative);
  1385. return;
  1386. }
  1387. // If we can retrieve the count of the collection without enumerating it
  1388. // (e.g.: the collections is a List<T>), use it to resize the array once
  1389. // instead of growing it as we add items.
  1390. if (collection.TryGetNonEnumeratedCount(out int count))
  1391. {
  1392. int oldCount = Count;
  1393. Resize(Count + count);
  1394. using var enumerator = collection.GetEnumerator();
  1395. for (int i = 0; i < count; i++)
  1396. {
  1397. enumerator.MoveNext();
  1398. this[oldCount + i] = enumerator.Current;
  1399. }
  1400. return;
  1401. }
  1402. foreach (var item in collection)
  1403. {
  1404. Add(item);
  1405. }
  1406. }
  1407. /// <summary>
  1408. /// Finds the index of an existing value using binary search.
  1409. /// If the value is not present in the array, it returns the bitwise
  1410. /// complement of the insertion index that maintains sorting order.
  1411. /// Note: Calling <see cref="BinarySearch(int, int, T)"/> on an unsorted
  1412. /// array results in unexpected behavior.
  1413. /// </summary>
  1414. /// <exception cref="ArgumentOutOfRangeException">
  1415. /// <paramref name="index"/> is less than 0.
  1416. /// -or-
  1417. /// <paramref name="count"/> is less than 0.
  1418. /// </exception>
  1419. /// <exception cref="ArgumentException">
  1420. /// <paramref name="index"/> and <paramref name="count"/> do not denote
  1421. /// a valid range in the <see cref="Array{T}"/>.
  1422. /// </exception>
  1423. /// <param name="index">The starting index of the range to search.</param>
  1424. /// <param name="count">The length of the range to search.</param>
  1425. /// <param name="item">The object to locate.</param>
  1426. /// <returns>
  1427. /// The index of the item in the array, if <paramref name="item"/> is found;
  1428. /// otherwise, a negative number that is the bitwise complement of the index
  1429. /// of the next element that is larger than <paramref name="item"/> or, if
  1430. /// there is no larger element, the bitwise complement of <see cref="Count"/>.
  1431. /// </returns>
  1432. public int BinarySearch(int index, int count, T item)
  1433. {
  1434. if (index < 0)
  1435. throw new ArgumentOutOfRangeException(nameof(index), "index cannot be negative.");
  1436. if (count < 0)
  1437. throw new ArgumentOutOfRangeException(nameof(count), "count cannot be negative.");
  1438. if (Count - index < count)
  1439. throw new ArgumentException("length is out of bounds or count is greater than the number of elements.");
  1440. if (Count == 0)
  1441. {
  1442. // Special case for empty array to avoid an interop call.
  1443. return -1;
  1444. }
  1445. using var variantValue = VariantUtils.CreateFrom(item);
  1446. var self = (godot_array)_underlyingArray.NativeValue;
  1447. return NativeFuncs.godotsharp_array_binary_search(ref self, index, count, variantValue);
  1448. }
  1449. /// <summary>
  1450. /// Finds the index of an existing value using binary search.
  1451. /// If the value is not present in the array, it returns the bitwise
  1452. /// complement of the insertion index that maintains sorting order.
  1453. /// Note: Calling <see cref="BinarySearch(T)"/> on an unsorted
  1454. /// array results in unexpected behavior.
  1455. /// </summary>
  1456. /// <param name="item">The object to locate.</param>
  1457. /// <returns>
  1458. /// The index of the item in the array, if <paramref name="item"/> is found;
  1459. /// otherwise, a negative number that is the bitwise complement of the index
  1460. /// of the next element that is larger than <paramref name="item"/> or, if
  1461. /// there is no larger element, the bitwise complement of <see cref="Count"/>.
  1462. /// </returns>
  1463. public int BinarySearch(T item)
  1464. {
  1465. return BinarySearch(0, Count, item);
  1466. }
  1467. /// <summary>
  1468. /// Clears the array. This is the equivalent to using <see cref="Resize(int)"/>
  1469. /// with a size of <c>0</c>
  1470. /// </summary>
  1471. /// <exception cref="InvalidOperationException">
  1472. /// The array is read-only.
  1473. /// </exception>
  1474. public void Clear()
  1475. {
  1476. _underlyingArray.Clear();
  1477. }
  1478. /// <summary>
  1479. /// Returns <see langword="true"/> if the array contains the given value.
  1480. /// </summary>
  1481. /// <example>
  1482. /// <code>
  1483. /// var arr = new Godot.Collections.Array&lt;string&gt; { "inside", "7" };
  1484. /// GD.Print(arr.Contains("inside")); // True
  1485. /// GD.Print(arr.Contains("outside")); // False
  1486. /// GD.Print(arr.Contains(7)); // False
  1487. /// GD.Print(arr.Contains("7")); // True
  1488. /// </code>
  1489. /// </example>
  1490. /// <param name="item">The item to look for.</param>
  1491. /// <returns>Whether or not this array contains the given item.</returns>
  1492. public bool Contains(T item) => IndexOf(item) != -1;
  1493. /// <summary>
  1494. /// Copies the elements of this <see cref="Array{T}"/> to the given
  1495. /// C# array, starting at the given index.
  1496. /// </summary>
  1497. /// <exception cref="ArgumentOutOfRangeException">
  1498. /// <paramref name="arrayIndex"/> is less than 0 or greater than the array's size.
  1499. /// </exception>
  1500. /// <param name="array">The C# array to copy to.</param>
  1501. /// <param name="arrayIndex">The index to start at.</param>
  1502. public void CopyTo(T[] array, int arrayIndex)
  1503. {
  1504. if (array == null)
  1505. throw new ArgumentNullException(nameof(array), "Value cannot be null.");
  1506. if (arrayIndex < 0)
  1507. {
  1508. throw new ArgumentOutOfRangeException(nameof(arrayIndex),
  1509. "Number was less than the array's lower bound in the first dimension.");
  1510. }
  1511. int count = Count;
  1512. if (array.Length < (arrayIndex + count))
  1513. {
  1514. throw new ArgumentException(
  1515. "Destination array was not long enough. Check destIndex and length, and the array's lower bounds.");
  1516. }
  1517. for (int i = 0; i < count; i++)
  1518. {
  1519. array[arrayIndex] = this[i];
  1520. arrayIndex++;
  1521. }
  1522. }
  1523. /// <summary>
  1524. /// Removes the first occurrence of the specified <paramref name="item"/>
  1525. /// from this <see cref="Array{T}"/>.
  1526. /// </summary>
  1527. /// <exception cref="InvalidOperationException">
  1528. /// The array is read-only.
  1529. /// </exception>
  1530. /// <param name="item">The value to remove.</param>
  1531. /// <returns>A <see langword="bool"/> indicating success or failure.</returns>
  1532. public bool Remove(T item)
  1533. {
  1534. ThrowIfReadOnly();
  1535. int index = IndexOf(item);
  1536. if (index >= 0)
  1537. {
  1538. RemoveAt(index);
  1539. return true;
  1540. }
  1541. return false;
  1542. }
  1543. // IEnumerable<T>
  1544. /// <summary>
  1545. /// Gets an enumerator for this <see cref="Array{T}"/>.
  1546. /// </summary>
  1547. /// <returns>An enumerator.</returns>
  1548. public IEnumerator<T> GetEnumerator()
  1549. {
  1550. int count = _underlyingArray.Count;
  1551. for (int i = 0; i < count; i++)
  1552. {
  1553. yield return this[i];
  1554. }
  1555. }
  1556. IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
  1557. /// <summary>
  1558. /// Converts this <see cref="Array{T}"/> to a string.
  1559. /// </summary>
  1560. /// <returns>A string representation of this array.</returns>
  1561. public override string ToString() => _underlyingArray.ToString();
  1562. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1563. public static implicit operator Variant(Array<T> from) => Variant.CreateFrom(from);
  1564. [MethodImpl(MethodImplOptions.AggressiveInlining)]
  1565. public static explicit operator Array<T>(Variant from) => from.AsGodotArray<T>();
  1566. private void ThrowIfReadOnly()
  1567. {
  1568. if (IsReadOnly)
  1569. {
  1570. throw new InvalidOperationException("Array instance is read-only.");
  1571. }
  1572. }
  1573. }
  1574. }