( (/*out*/ string uname) => .... ...">

Is there any trick to use the "out" parameters inside the lambda function?

if ( (new Func</*out*/ string, bool>( (/*out*/ string uname) => .... 

more details: this is part of the login function, and I just want my lambda function to change the login username with the out parameter and tell me that the user has connected to it bool return.

I really understand that I can return a Tuple and then get the value of the string, but I want to specify the parameter exactly for some personal clarity. Iโ€™d better return only the null string if the user is not logged in, I just want to know if I can use the parameters inside the lambda functions.

And I really understand that code with expressions in operator locations is not so clean, but no one told me that this is really bad for the compiler.

+8
c # lambda
source share
3 answers

Lambda expressions will not work, but for delegates you should be fine using the operator 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); 
+5
source share

You cannot use parameters with a lambda expression. See this question https://stackoverflow.com/a/4646263

+2
source share

While you cannot use the out keyword, I have found a solution that allows you to mainly use C ++ style memory pointers in .NET. I found this class because you opened this SO question without being able to use the 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 cleanup with RavenDB when I need fine-grained session control, as well as leaving the context of the environment context. A word of warning I have no idea what consequences this type of code will have in a long working application, as I'm not sure if this will confuse the GC and will not lead to memory recovery.

+2
source share

All Articles