GD0302.rst 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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 type <c_sharp_variant_compatible_types>` is expected,
  15. but the specified generic type is not annotated with the ``[MustBeVariant]``
  16. attribute.
  17. Rule description
  18. ----------------
  19. When a generic type parameter is annotated with the ``[MustBeVariant]`` attribute,
  20. the generic type is required to be a Variant-compatible type. When the type used
  21. is also a generic type, this generic type must be annotated with the ``[MustBeVariant]``
  22. attribute as well. For example, the generic ``Godot.Collections.Array<T>`` type
  23. only supports items of a type that can be converted to Variant, a generic type
  24. can be specified if it's properly annotated.
  25. .. code-block:: csharp
  26. public void Method1<T>()
  27. {
  28. // T is not valid here because it may not a Variant-compatible type.
  29. var invalidArray = new Godot.Collections.Array<T>();
  30. }
  31. public void Method2<[MustBeVariant] T>()
  32. {
  33. // T is guaranteed to be a Variant-compatible type because it's annotated
  34. // with the [MustBeVariant] attribute, so it can be used here.
  35. var validArray = new Godot.Collections.Array<T>();
  36. }
  37. How to fix violations
  38. ---------------------
  39. To fix a violation of this rule, add the ``[MustBeVariant]`` attribute to the
  40. generic type that is used as a generic type argument that must be Variant-compatible.
  41. When to suppress warnings
  42. -------------------------
  43. Do not suppress a warning from this rule. API that contains generic type arguments
  44. annotated with the ``[MustBeVariant]`` attribute usually has this requirement
  45. because the values will be passed to the engine, if the type can't be marshalled
  46. it will result in runtime errors.