# GetOrAddComponent<T>()

> Returns a reference to the component of type T attached to this element. If the component is not attached yet, it is added first.

## Definition

* **Type:** Method
* **Namespace:** [UnityEngine.UIElements](/engine/6000.7/script-reference/unityengine/uielements.md)
* **Assembly:** UnityEngine.UIElementsModule

```csharp
public ref T GetOrAddComponent<T>() where T : struct, IVisualElementComponent
```

### Returns

| Type | Description                                                                                                                                                                                                                                         |
| ---- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| T    | A reference to the live component data. Like [VisualElement.GetComponent](/engine/6000.7/script-reference/unityengine/uielements/visualelement/getcomponent.md), the reference is valid until a component is added to or removed from this element. |

### Remarks

When the component is already attached, this method behaves exactly like [VisualElement.GetComponent](/engine/6000.7/script-reference/unityengine/uielements/visualelement/getcomponent.md) and the component data is not changed. When it is not attached, a new component is created and added the same way as [VisualElement.AddComponent](/engine/6000.7/script-reference/unityengine/uielements/visualelement/addcomponent.md). The new component is created with the type's [UxmlCreateInstanceMethodAttribute](/engine/6000.7/script-reference/unityengine/uielements/uxmlcreateinstancemethodattribute.md) method when the type has one, otherwise with default values.
