Is there some trick to use 'out' parameters inside lambda function?

Lambda expressions won't work, but for delegates you should be fine using a statement body:

bool outval = false; // definite assignment
Func<bool> func = () => {
    return SomeMethod(out foo);
};
bool returned = func();
// check both outval and returned

For delegates... You will need to define your own:

public delegate bool MyType(out string value);

You cannot use out parameters with a lambda expression. See this Stack Overflow question.


While you can't use the out keyword I did find a solution that lets you basically achieve C++ style memory pointers in .NET. I found this class due to the very reason you opened this SO question not being able to use an out parameter where I wanted it.

public class Ptr<T>
{
    Func<T> getter;
    Action<T> setter;

    public Ptr(Func<T> g, Action<T> s)
    {
        getter = g;
        setter = s;
    }

    public T Deref
    {
        get { return getter(); }
        set { setter(value); }
    }
}

Usage example

private IDocumentSession _session = DocumentStore.OpenSession()

var ptr = new Ptr<IDocumentSession>(
                () => _session, 
                newValue => _session = newValue))

session.Deref.SaveChanges();
session.Deref = DocumentStore.OpenSession();

I use this in a batch program that allows batch operations to control session flushing with RavenDB when I need fine grained session control while also leaving an ambient session context. Word of warning I have no idea what implications this type of code would have in a long running production app since I'm not sure if this would confuse the GC and cause memory to never be reclaimed.

Tags:

C#

Lambda