GD0302.rst 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. GD0302: The generic type parameter must be annotated with the MustBeVariant attribute
  2. =====================================================================================
  3. ==================================== ======================================
  4. Value
  5. ==================================== ======================================
  6. **Rule ID** GD0302
  7. **Category** Usage
  8. **Fix is breaking or non-breaking** Breaking
  9. **Enabled by default** Yes
  10. ==================================== ======================================
  11. Cause
  12. -----
  13. A generic type is specified for a generic type argument when a
  14. :ref:`Variant-compatible <doc_c_sharp_variant>` type is expected, but the
  15. specified generic type is not annotated with the ``[MustBeVariant]`` attribute.
  16. Rule description
  17. ----------------
  18. When a generic type parameter is annotated with the ``[MustBeVariant]`` attribute,
  19. the generic type is required to be a Variant-compatible type. When the type used
  20. is also a generic type, this generic type must be annotated with the ``[MustBeVariant]``
  21. attribute as well. For example, the generic ``Godot.Collections.Array<T>`` type
  22. only supports items of a type that can be converted to Variant, a generic type
  23. can be specified if it's properly annotated.
  24. .. code-block:: csharp
  25. public void Method1<T>()
  26. {
  27. // T is not valid here because it may not a Variant-compatible type.
  28. var invalidArray = new Godot.Collections.Array<T>();
  29. }
  30. public void Method2<[MustBeVariant] T>()
  31. {
  32. // T is guaranteed to be a Variant-compatible type because it's annotated
  33. // with the [MustBeVariant] attribute, so it can be used here.
  34. var validArray = new Godot.Collections.Array<T>();
  35. }
  36. How to fix violations
  37. ---------------------
  38. To fix a violation of this rule, add the ``[MustBeVariant]`` attribute to the
  39. generic type that is used as a generic type argument that must be Variant-compatible.
  40. When to suppress warnings
  41. -------------------------
  42. Do not suppress a warning from this rule. API that contains generic type arguments
  43. annotated with the ``[MustBeVariant]`` attribute usually has this requirement
  44. because the values will be passed to the engine, if the type can't be marshalled
  45. it will result in runtime errors.