Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to circumvent using an out parameter in an anonymous method block?

The following method does not compile. Visual Studio warns "An out parameter may not be used within an anonymous method". The WithReaderLock(Proc action) method takes a delegate void Proc().

public Boolean TryGetValue(TKey key, out TValue value)
{
    Boolean got = false;
    WithReaderLock(delegate
    {
        got = dictionary.TryGetValue(key, out value);
    });
    return got;
}

What's the best way to get this behavior? (Please refrain from providing advice on threadsafe dictionaries, this question is intended to solve the out parameter problem in general).

like image 295
Anthony Mastrean Avatar asked Dec 21 '08 20:12

Anthony Mastrean


2 Answers

public bool TryGetValue(TKey key, out TValue value)
{
    bool got = false;            
    TValue tmp = default(TValue); // for definite assignment
    WithReaderLock(delegate
    {
        got = dictionary.TryGetValue(key, out tmp);
    });
    value = tmp;
    return got;
}

(edited - small bug)

For info, in .NET 3.5 you might want to use the Action delegate instead of rolling your own, since people will recognise it more. Even in 2.0, there are lots of void Foo() delegates: ThreadStart, MethodInvoker, etc - but Action is the easiest to follow ;-p

like image 88
Marc Gravell Avatar answered Nov 17 '22 09:11

Marc Gravell


The simple answer is to just copy the logic inside the method. But then we stretch the DRY principle and have to maintain behavior inside both methods.

public Boolean TryGetValue(TKey key, out TValue value)
{
    internalLock.AcquireReaderLock(Timeout.Infine);
    try
    {
        return dictionary.TryGetValue(key, out value);
    }
    finally
    {
        internalLock.ReleaseReaderLock();
    }
}
like image 32
Anthony Mastrean Avatar answered Nov 17 '22 10:11

Anthony Mastrean