How to return value from Action ()?

As for the answer to this question Passing a DataContext to Action () , how do I return a value from an action (db)?

SimpleUsing.DoUsing(db => { // do whatever with db }); 

It should be more like:

 MyType myType = SimpleUsing.DoUsing<MyType>(db => { // do whatever with db. query buit using db returns MyType. }); 
+73
c # linq
Nov 11 '11 at 20:35
source share
4 answers

Your static method should go from:

 public static class SimpleUsing { public static void DoUsing(Action<MyDataContext> action) { using (MyDataContext db = new MyDataContext()) action(db); } } 

To:

 public static class SimpleUsing { public static TResult DoUsing<TResult>(Func<MyDataContext, TResult> action) { using (MyDataContext db = new MyDataContext()) return action(db); } } 

This answer grew out of comments so I can provide the code. For full development, see @sll answer below.

+81
Nov 11 '11 at 20:53
source share
— -

You can use the generic delegate Func<T, TResult> . (See MSDN )

 Func<MyType, ReturnType> func = (db) => { return new MyType(); } 

There are also useful generic delegates that take into account the return value:

  • Converter<TInput, TOutput> ( MSDN )
  • Predicate<TInput> - always return bool ( MSDN )



Method:

 public MyType SimpleUsing.DoUsing<MyType>(Func<TInput, MyType> myTypeFactory) 

General delegate:

 Func<InputArgumentType, MyType> createInstance = db => return new MyType(); 

Performance:

 MyType myTypeInstance = SimpleUsing.DoUsing( createInstance(new InputArgumentType())); 

OR explicitly:

 MyType myTypeInstance = SimpleUsing.DoUsing(db => return new MyType()); 
+102
Nov 11 2018-11-11T00:
source share

You can also take advantage of the fact that a lambda or anonymous method can close variables in its scope.

 MyType result; SimpleUsing.DoUsing(db => { result = db.SomeQuery(); //whatever returns the MyType result }); //do something with result 
+13
Nov 11 '11 at 20:52
source share

Use Func<T> instead of Action<T> .

Action<T> acts like a void method with a parameter of type T, while Func<T> works like a function without parameters and returns an object of type T. If you want to set the parameters of your function, use Func<TReturn, TParameter> .

+2
Jun 10 '19 at 18:35
source share



All Articles