c_sharp_variant.rst 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. .. _doc_c_sharp_variant:
  2. C# Variant
  3. ==========
  4. For a detailed explanation of Variant in general, see the :ref:`Variant <class_Variant>` documentation page.
  5. ``Godot.Variant`` is used to represent Godot's native :ref:`Variant <class_Variant>` type. Any Variant-compatible type can be converted from/to it.
  6. We recommend avoiding ``Godot.Variant`` unless it is necessary to interact with untyped engine APIs.
  7. Take advantage of C#'s type safety when possible.
  8. Converting from a Variant-compatible C# type to ``Godot.Variant`` can be done using implicit
  9. conversions. There are also ``CreateFrom`` method overloads and the generic ``Variant.From<T>``
  10. methods. Only the syntax is different: the behavior is the same.
  11. .. code-block:: csharp
  12. int x = 42;
  13. Variant numberVariant = x;
  14. Variant helloVariant = "Hello, World!";
  15. Variant numberVariant2 = Variant.CreateFrom(x);
  16. Variant numberVariant3 = Variant.From(x);
  17. Implicit conversions to ``Godot.Variant`` make passing variants as method arguments very convenient.
  18. For example, the third argument of :ref:`tween_property<class_Tween_method_tween_property>`
  19. specifying the final color of the tween is a ``Godot.Variant``.
  20. .. code-block:: csharp
  21. Tween tween = CreateTween();
  22. tween.TweenProperty(GetNode("Sprite"), "modulate", Colors.Red, 1.0f);
  23. Converting from ``Godot.Variant`` to a C# type can be done using explicit conversions. There are
  24. also ``Variant.As{TYPE}`` methods and the generic ``Variant.As<T>`` method. All of these behave the
  25. same.
  26. .. code-block:: csharp
  27. int number = (int)numberVariant;
  28. string hello = (string)helloVariant;
  29. int number2 = numberVariant.As<int>();
  30. int number3 = numberVariant.AsInt32();
  31. .. note::
  32. The ``Variant.As{TYPE}`` methods are typically named after C# types (``Int32``), not C# keywords
  33. (``int``).
  34. If the Variant type doesn't match the conversion target type, the consequences vary depending on the
  35. source and target values.
  36. - The conversion may examine the value and return a similar but potentially unexpected value of the
  37. target type. For example, the string ``"42a"`` may be converted to the integer ``42``.
  38. - The default value of the target type may be returned.
  39. - An empty array may be returned.
  40. - An exception may be thrown.
  41. Converting to the correct type avoids complicated behavior and should be preferred.
  42. The ``Variant.Obj`` property returns a C# ``object`` with the correct value for any variant. This
  43. may be useful when the type of Variant is completely unknown. However, when possible, prefer more
  44. specific conversions. ``Variant.Obj`` evaluates a ``switch`` on ``Variant.VariantType`` and it may
  45. not be necessary. Also, if the result is a value type, it may be boxed when it normally wouldn't be.
  46. For example, if the potential for ``Variant.As<MyNode>()`` to throw a invalid cast exception isn't
  47. acceptable, consider using a ``Variant.As<GodotObject>() is MyNode n`` type pattern instead.
  48. .. note::
  49. Since the Variant type in C# is a struct, it can't be null. To create a "null"
  50. Variant, use the ``default`` keyword or the ``Godot.Variant`` parameterless constructor.
  51. Variant-compatible types
  52. ------------------------
  53. * All the `built-in value types <https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/built-in-types-table>`_,
  54. except ``decimal``, ``nint`` and ``nuint``.
  55. * ``string``.
  56. * Classes derived from :ref:`GodotObject <class_Object>`.
  57. * Collections types defined in the ``Godot.Collections`` namespace.
  58. Full list of Variant types and their equivalent C# type:
  59. ======================= ===========================================================
  60. Variant.Type C# Type
  61. ======================= ===========================================================
  62. ``Nil`` ``null`` (Not a type)
  63. ``Bool`` ``bool``
  64. ``Int`` ``long`` (Godot stores 64-bit integers in Variant)
  65. ``Float`` ``double`` (Godot stores 64-bit floats in Variant)
  66. ``String`` ``string``
  67. ``Vector2`` ``Godot.Vector2``
  68. ``Vector2I`` ``Godot.Vector2I``
  69. ``Rect2`` ``Godot.Rect2``
  70. ``Rect2I`` ``Godot.Rect2I``
  71. ``Vector3`` ``Godot.Vector3``
  72. ``Vector3I`` ``Godot.Vector3I``
  73. ``Transform2D`` ``Godot.Transform2D``
  74. ``Vector4`` ``Godot.Vector4``
  75. ``Vector4I`` ``Godot.Vector4I``
  76. ``Plane`` ``Godot.Plane``
  77. ``Quaternion`` ``Godot.Quaternion``
  78. ``Aabb`` ``Godot.Aabb``
  79. ``Basis`` ``Godot.Basis``
  80. ``Transform3D`` ``Godot.Transform3D``
  81. ``Projection`` ``Godot.Projection``
  82. ``Color`` ``Godot.Color``
  83. ``StringName`` ``Godot.StringName``
  84. ``NodePath`` ``Godot.NodePath``
  85. ``Rid`` ``Godot.Rid``
  86. ``Object`` ``Godot.GodotObject`` or any derived type.
  87. ``Callable`` ``Godot.Callable``
  88. ``Signal`` ``Godot.Signal``
  89. ``Dictionary`` ``Godot.Collections.Dictionary``
  90. ``Array`` ``Godot.Collections.Array``
  91. ``PackedByteArray`` ``byte[]``
  92. ``PackedInt32Array`` ``int[]``
  93. ``PackedInt64Array`` ``long[]``
  94. ``PackedFloat32Array`` ``float[]``
  95. ``PackedFloat64Array`` ``double[]``
  96. ``PackedStringArray`` ``string[]``
  97. ``PackedVector2Array`` ``Godot.Vector2[]``
  98. ``PackedVector3Array`` ``Godot.Vector3[]``
  99. ``PackedColorArray`` ``Godot.Color[]``
  100. ======================= ===========================================================
  101. .. warning::
  102. Godot uses 64-bit integers and floats in Variant. Smaller integer and float types
  103. such as ``int``, ``short`` and ``float`` are supported since they can fit in the
  104. bigger type. Be aware that when a conversion is performed, using the wrong
  105. type will result in potential precision loss.
  106. .. warning::
  107. Enums are supported by ``Godot.Variant`` since their underlying type is an integer
  108. type which are all compatible. However, implicit conversions don't exist, enums must
  109. be manually converted to their underlying integer type before they can converted to/from
  110. ``Godot.Variant`` or use the generic ``Variant.As<T>`` and ``Variant.From<T>`` methods
  111. to convert them.
  112. .. code-block:: csharp
  113. enum MyEnum { A, B, C }
  114. Variant variant1 = (int)MyEnum.A;
  115. MyEnum enum1 = (MyEnum)(int)variant1;
  116. Variant variant2 = Variant.From(MyEnum.A);
  117. MyEnum enum2 = variant2.As<MyEnum>();
  118. Using Variant in a generic context
  119. ----------------------------------
  120. When using generics, you may be interested in restricting the generic ``T`` type to be
  121. only one of the Variant-compatible types. This can be achieved using the ``[MustBeVariant]``
  122. attribute.
  123. .. code-block:: csharp
  124. public void MethodThatOnlySupportsVariants<[MustBeVariant] T>(T onlyVariant)
  125. {
  126. // Do something with the Variant-compatible value.
  127. }
  128. Combined with the generic ``Variant.From<T>`` allows you to obtain an instance of ``Godot.Variant``
  129. from an instance of a generic ``T`` type. Then it can be used in any API that only supports the
  130. ``Godot.Variant`` struct.
  131. .. code-block:: csharp
  132. public void Method1<[MustBeVariant] T>(T variantCompatible)
  133. {
  134. Variant variant = Variant.From(variantCompatible);
  135. Method2(variant);
  136. }
  137. public void Method2(Variant variant)
  138. {
  139. // Do something with variant.
  140. }
  141. In order to invoke a method with a generic parameter annotated with the ``[MustBeVariant]``
  142. attribute, the value must be a Variant-compatible type or a generic ``T`` type annotated
  143. with the ``[MustBeVariant]`` attribute as well.
  144. .. code-block:: csharp
  145. public class ObjectDerivedClass : GodotObject { }
  146. public class NonObjectDerivedClass { }
  147. public void Main<[MustBeVariant] T1, T2>(T1 someGeneric1, T2 someGeneric2)
  148. {
  149. MyMethod(42); // Works because `int` is a Variant-compatible type.
  150. MyMethod(new ObjectDerivedClass()); // Works because any type that derives from `GodotObject` is a Variant-compatible type.
  151. MyMethod(new NonObjectDerivedClass()); // Does NOT work because the type is not Variant-compatible.
  152. MyMethod(someGeneric1); // Works because `T1` is annotated with the `[MustBeVariant]` attribute.
  153. MyMethod(someGeneric2); // Does NOT work because `T2` is NOT annotated with the `[MustBeVariant]` attribute.
  154. }
  155. public void MyMethod<[MustBeVariant] T>(T variant)
  156. {
  157. // Do something with variant.
  158. }