I don't understand why I'm getting the CS8347 error while trying to make an extension method

Viewed 200

I was trying to create a simple extension method wrapper around CollectionsMarshal.GetValueRefOrAddDefault(..) and I ran into a problem I don't quite understand.

This code works:

public static ref TValue? GetValueRefOrAddDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key, out bool exists)
    where TKey : notnull
{
    return ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out exists);
}

If I try not to pass the out bool exists variable outside of the method by discarding it or by just storing it in a local variable, it doesn't work:

public static ref TValue? GetValueRefOrAddDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
    where TKey : notnull
{
    return ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out _);
    // Error: Cannot use a result of CollectionsMarshal.GetValueRefOrAddDefault(..) in this context because
    // it may expose variables referenced by parameter 'exists' outside of their declaration scope
}

To me this error sounds a lot like something I should get when trying to return a reference to a local variable. I just don't get why I'm getting the error by simply not using / passing out the boolean I received, and how could that omission possibly reference anything out of scope.

Also, the error disappears when I use a dummy variable outside of the scope of the method, but I'd rather not do that:

private static bool dummy;
public static ref TValue? GetValueRefOrAddDefault<TKey, TValue>(this Dictionary<TKey, TValue> dictionary, TKey key)
    where TKey : notnull
{
    return ref CollectionsMarshal.GetValueRefOrAddDefault(dictionary, key, out dummy);
}
0 Answers
Related