C# Is there a way to use ref return as an out parameter?

71 views Asked by At

I am playing around with LeoEcs and I keep writing the following code:

if(!entity.HasComponent<T>())
    return;
ref T comp = ref entity.GetComponent<T>();

This looks pretty tame, but it gets very boilerplaty when you need to check for multiple params at the same time. I would like to join those together into something like:

if(!entity.HasComponent(out ref T comp))
    return;

I've tried out ref, it obviously didn't work, but I am wondering if there is a workaround.

Edit: T is a struct, whose value is stored in an array. I need the ref keyword to be able to modify the actual value, instead of its copy.

1

There are 1 answers

2
X3R0 On

here is a workaround if you want to achieve a similar effect.

ref var comp = ref entity.GetComponentRef<T>();
public ref T GetComponentRef<T>(int entityId) where T : struct
{
    if (!HasComponent<T>(entityId))
    {
        throw new InvalidOperationException($"Component {typeof(T)} not found for entity {entityId}");
    }

    return ref components[GetIndex<T>(entityId)];
}