Is there a way to execute a lambda expression immediately after its definition?
In other words (Invalid C# code):
(() => { Console.WriteLine("Hello World"); }).Invoke();
Sure.
new Action(() => { Console.WriteLine("Hello World"); })();
That should do the trick.
Another "option", which is just the other two answers in a slightly different guise:
((Action)(() => { Console.WriteLine("Hello World"); }))();
The reason, as directly taken from phoog's comment:
...you haven't told the compiler whether you want an Action or an Expression<Action>. If you cast that lambda expression to Action, you'll be able to call Invoke on it or use the method-call syntax () to invoke it.
It sure gets ugly though, and I do not know of a place where this form is ever useful, as it cannot be used for recursion without a name...
You should be able to do this:
Action runMe = () => { Console.WriteLine("Hello World"); };
runMe();
Here's an example of how this might be used. You want to initialize a constructor with the result of a few lines of code that can't be written as a function because that is how the 3rd party API is structured.
It is just glue code to prevent writing a standalone function that is never called anywhere else. I'm using Func instead of Action, but the answer is the same as user166390.
// imagine several dozens of lines that look like this
// where the result is the return value of a function call
fields.Add(new ProbeField(){
Command = "A",
Field = "Average",
Value = be.GetAverage()
});
// now you need something that can't be expressed as function call
// so you wrap it in a lambda and immediately call it.
fields.Add(new ProbeField(){
Command = "C",
Field = "Cal Coeff",
Value = ((Func<string>)(() => {
CalCoef coef;
Param param;
be.GetCalibrationCoefficients(out coef, out param);
return coef.lowDet1.ToString();
}))()
});
For my own projects I've sometimes written a tiny reusable helper function to make the syntax for an immediately invoked lambda look shorter. This 'Inv' was inspired by the similar 'fun' function in the LanguageExt library.
// Helper utility functions
public static void Inv(Action a) => a();
public static T Inv<T>(Func<T> f) => f();
private static void TestMethod()
{
// Action example
Inv(() => Console.WriteLine("Hello World!"));
// Func example with no parameters
bool result = Inv(() =>
{
if (1 == 1)
return true;
else
return false;
});
}
You could also extend this with a few other overloads to make it so you could pass in parameters, but these look a bit more cumbersome syntax wise and may not be as helpful.
public static Func<A, T> Inv<A, T>(Func<A, T> f) => f;
public static Func<A, B, T> Inv<A, B, T>(Func<A, B, T> f) => f;
string printNumber = Inv((int number) => $"This is the number {number}")(5);
int addedNumbers = Inv((int x, int y) => x + y)(5, 6);
using System.Threading.Tasks;
using System.Threading;
Task.Run(()=>{
//do something
});
programmers really like to make things more difficult than they should be
You can add a 500ms delay with
Task.Run(()=>{
Thread.Sleep(500);
//do something
});
and then the next logical extension is passing parameters to your anonymous function. You can do this with scope:
var x=1;
Task.Run(()=>{
x++;
});
and then you can basically throw the rest of C# out the window. If you like this functional style, I suggest JS or C.
Related
In javascript we can do this:
var arr = [];
function fooBar() {
console.log('Hello World');
}
arr[0] = fooBar;
arr[0]();
Essentially each function is a real object and I can store them in an array if I want to. My question is, since C# doesnt have pointers, what is the best way to handle such as scenario? I mean how can I store function references into arrays?
I know we have something called delegates but im not sure if this is the right thing for the task...
Delegates are exactly what you need:
var list = new List<Action>();
...
void fooBar() {
....
}
...
list.Add(fooBar);
The Action is actually nothing but a delegate, simply look its definiton and you´ll see it is similar to a delegate expecting nothing and returning nothing. If you want to pass parameters use any of it´s generic versions, for example Action<T>. If you also need to add methods that return something use the Func-delegate instead.
EDIT: Every delegate has its own type so you can´t mix them and put them alltogether into one single collection, except you use a collection of type Delegate:
var list = new List<Delegate>();
In this case you can´t use urual braces to call the actual delegate, instead you have to use DynamicInvoke and pass the arguments according to the delegates signature.
list[0].DynamicInvoke(args);
Delegates are the right thing for the task - they're equivalent to a strongly-typed function pointer.
Because each delegate is its own type you cannot mix-and-match different delegate types in an array type to a single delegate-type, you can use the parent System.Delegate to allow you to store delegates of different types in the array, though you lose the ability to invoke them directly without some side-channel that informs your program of their arguments.
For example:
public static String Meow(Cat cat) { return "meow"; }
public static String Purr(Cat cat) { return "purr"; }
delegate String CatSound(Cat cat);
CatSound[] catSounds = new CatSound[] {
Meow,
Purr
};
You can then invoke them directly:
Cat orion = new Cat();
catSounds[0]( orion ); // meow
catSounds[1]( orion ); // purr
If you want to add a DogSound delegate to your collection, you'll have a harder job: you need to use Delegate[] instead...
delegate String DogSound(Dog dog);
Delegate[] petSounds = new Delegate[] {
new CatSound( Meow ),
new CatSound( Purr ),
new DogSound( Woof ),
new DogSound( Bark ),
}; // note that C# compiler allows shorthand syntax where simply `Meow` is behind-the-scenes converted into `new CatSound( Meow )`.
...and you have to invoke it using the DynamicInvoke method ( https://msdn.microsoft.com/en-us/library/system.delegate.dynamicinvoke(v=vs.110).aspx ) which means you'll lose compile-time verification of correct arguments, instead any call made with incorrect arguments will fail at runtime with a MemberAccessException.
Dog pupper = new Dog();
Cat orion = new Cat();
petSounds[0].DynamicInvoke( orion );
petSounds[1].DynamicInvoke( orion );
petSounds[2].DynamicInvoke( pupper ); // ok, this is a DogSound
petSounds[3].DynamicInvoke( orion ); // this will fail at runtime because you're passing a Cat into a DogSound delegate
You can also think of delgates as "an interface for a single method".
Prior to the .NET Framework 3.5, you generally needed to define your own delegate types using the delegate keyword (note that the delegate keyword is also overloaded for anonymous functions in C# 3.0), however there is now System.Action and System.Func which serve 95% of cases where you would have previously needed to define your own type. Indeed, today my delegate CatSound is unnecessary, you could just use Func<Cat,String> instead.
Given that the functions to call have the same signature, it could be done by using the predefined generics for delegates as follows.
Func<int,int> Square = x => x*x;
Func<int,int> Successor = x => x+1;
Func<int,int> Functions[] = new Func<int,int>[]{ Square, Successor };
int A = Functions[0](2); // A gets assigned 4;
int B = Functions[1](1); // B gets assigned 2;
You could Store Action or Func objects, someting like:
void Main()
{
var arr = new object[2];
arr[0] = 1;
arr[1] = (Action)DoIt;
foreach (var a in arr)
{
if (a is Action)
{
((Action)a)();
}
else
{
Console.WriteLine(a.ToString());
}
}
}
public void DoIt()
{
Console.WriteLine("did");
}
Consider actions (depending on .net verion)
https://msdn.microsoft.com/en-us/library/018hxwa8(v=vs.110).aspx
List<Action<string>> actions = new List<Action<string>>();
actions.Add(() => {
//do stuff
});
or if you need rturn values use Func: https://msdn.microsoft.com/en-us/library/bb549151(v=vs.110).aspx
yea through delegates you can:
static void iammain()
{
List<Action> lst = new List<Action>();
lst.AddRange(new Action[] { proc1, proc2, proc3 });
for (int i = 0; i < lst.Count; i++)
{
lst[i]();
}
}
static void proc1()
{
Console.WriteLine("i am proc1");
}
static void proc2()
{
Console.WriteLine("i am proc2");
}
static void proc3()
{
Console.WriteLine("i am proc3");
}
Let's consider this code:
public void DoSomething<T>(Func<T> MyFunc)
{
var NewLazyItem = new Lazy<T>(MyFunc);
// do stuff
// use the NewLazyItem
}
And let's say I have a method like this:
public int Add(int a, int b) { return a + b; }
What I would like to achieve is to be able to pass the Add method to the DoSomething method but with parameters along.
Ideally I could pass Add, 2 and 3 and when the NewLazy item gets used, Add(2, 3) gets called.
I tried various ideas, but I can't find a way to make it work.
Unless I'm misunderstanding the question, the simplest way is just to include the parameters as closures for a lambda expression:
var x = 2;
var y = 3;
DoSomething(() => Add(x, y));
I am trying to chain a bunch of functions calls into one callback function ptr (using Action) and each of those function calls take different arguments (so can't use delegates which would be ideal, unless I am missing something :)) So this is what I did:
for (int i=0; i<num_func_calls; ++i)
{
// could be anything different for each call
int call_id = i;
Action old_action = lastAction;
lastAction = new Action(() =>
{
FuncCall(call_id, true);
old_action();
});
}
It works as I expect it to, but the question is: is this efficient/correct? Are there any gotcha's or things I need to worry about with this?
Thanks!
Here is an example using higher order functions.
static Action Apply(IEnumerable<int> data)
{
Action zero = () => { };
return data.Aggregate(zero,
(a, id) => a + (() => FuncCall(id, true)));
}
This would be a great case to use a Task, since it has .ContinueWith which tells the task to run another task when it's complete. You can chain them together.
http://msdn.microsoft.com/en-us/library/dd270696.aspx
Also, you could reduce the delegate use by doing this:
() => {
for (int i=0; i<num_func_calls; ++i) FuncCall(i, true);
}
I'm not entirely sure what it is you're asking but I'm just going to address a couple of things in your post which are wrong.
Firstly; Action is a Delegate it's just one that accepts a single parameter and does not return a value. If I have some Action call it A - Delegate d = A; will compile and run.
Secondly, to pass args in a general manner (meaning to some arbitrary function) you can use DynamicInvoke and wrap your arguments in an object array. As long as the items in the array are of the right types and are in the right order the method will correctly execute. Otherwise it will throw.
DynamicInvoke has a specific application but as an example if you provide me with an Object[] and a Delegate I can use DynamicInvoke to invoke the function without knowing what it's definition is. Like;
myDelegate.DynamicInvoke(args); // where args is an Object[]
In general, you only want to use it when you're deciding which delegates to call at run time.
Good evening,
I was wondering if I could do something like:
while(true)
{
MyEnum currentValue = GetMyEnumValueFromDB();
if(currentValue == MyEnum.BreakIfYouGetThis)
break;
else if(currentValue == MyEnum.AlsoBreakIfYouGetThis)
break;
else
//Do some computing
}
But instead of having a while(true) loop, I'd want to encapsulate the conditional logic in a Func and execute it like this:
while(new Func<bool>(/* what goes here? */))
{
//Do some computing
}
In my case at least, it would look much cleaner, but i'm not sure how to do it (kinda new at Func/Action..).
EDIT hope this clarifies:
It could also be done like this:
while(GetMyEnumValueFromDB() != MyEnum.BreakIfYouGetThis &&
GetMyEnumValueFromDB() != MyEnum.AlsoBreakIfYouGetThis)
{
//Do some computing
}
But that's 2 call to the database...
Thanks =)
Well you could have:
Func<bool> condition = ...;
while (condition())
{
}
Is that what you're thinking of? It's not really clear...
EDIT: In the example you've given, I'd use something like:
private static readonly MyEnum[] BreakEnumValues = {
MyEnum.BreakIfYouGetThis,
MyEnum.AlsoBreakIfYouGetThis
};
...
while (!BreakEnumValues.Contains(GetMyEnumValueFromDB()))
{
...
}
Or:
private static bool ShouldBreak(MyEnum enumFromDatabase)
{
return enumFromDatabase == MyEnum.BreakIfYouGetThis ||
enumFromDatabase == MyEnum.AlsoBreakIfYouGetThis;
}
...
while (!ShouldBreak(GetMyEnumValueFromDB))
{
...
}
EDIT: To counter KeithS's answer, this is entirely valid:
while (new Func<bool>(() => {
Console.WriteLine("Evaluating...");
return true;
})()) {
Console.WriteLine("In loop");
count++;
if (count == 5)
{
break;
}
}
It's horrible, but it's valid. (It can be made slightly less horrid by explicitly calling Invoke, but it's still not nice.)
You could do that, but if you don't have a compelling reason to do so (like you're passing the condition function in as a parameter), I'd just wrap your logic in a function and call it directly:
while(KeepGoing())
{
//Do stuff
}
bool KeepGoing()
{
// Check conditions for continuing
var value = GetMyEnumValueFromDB();
return value != MyEnum.BreakIfYouGetThis && value != MyEnum.AlsoBreakIfYouGetThis;
}
First off, a database call in a while loop is a bad idea. Query what you'll need beforehand and loop accordingly.
It appears that polymorphism can be your friend here. If you need to keep the same flow, you can do something like this:
interface IWhileLoopContinuable
{
bool KeepGoing {get;}
void DoWork();
}
Then you can use TakeWhile on this enumerable:
foreach(var item in queriedAsIWhileLoopContinuable.TakeWhile(c => c.KeepGoing))
{
item.DoWork();
}
All that being said, you could just query for what you want and work on that.
Well, first off you cannot "new" a Func, just like you can't new up any delegate type. You must instead assign an existing named method or function literal (aka anonymous delegate, lambda, etc) to initialize a Func variable.
//these won't compile; Func has no constructor
Func<bool> condition = new Func<bool>();
//As Jon Skeet notes, these will compile because of language-provided syntax,
//even though Funcs have no constructor with a delegate parameter.
Func<bool> condition = new Func<bool>(SomeNamedMethodReturnsBool);
Func<bool> condition = new Func<bool>(()=>true);
//and these will compile because you're directly assigning the delegate
Func<bool> condition = SomeNamedMethodReturnsBool;
Func<bool> condition = ()=>true;
You actually cannot do what you want in C#; an anonymous delegate must be assigned to a variable or parameter in order to be used. It cannot be used in-place as a "function literal" in the abstract sense.
Even if you could, the utility of such a statement escapes me. The delegate would not be re-instantiated every time (the compiler turns anonymous delegates into named private functions of the containing class, with mashup names), but you're adding a layer onto the call stack just to evaluate a constant expression that could be placed directly into the parenthesis of the while() statement. The main utility of an anonymous delegate would be that you could swap out lambdas at runtime, and in order to do that you MUST have a variable.
I have a question about the performance of dynamic in C#. I've read dynamic makes the compiler run again, but what does it do?
Does it have to recompile the whole method with the dynamic variable used as a parameter or just those lines with dynamic behavior/context?
I've noticed that using dynamic variables can slow down a simple for loop by 2 orders of magnitude.
Code I have played with:
internal class Sum2
{
public int intSum;
}
internal class Sum
{
public dynamic DynSum;
public int intSum;
}
class Program
{
private const int ITERATIONS = 1000000;
static void Main(string[] args)
{
var stopwatch = new Stopwatch();
dynamic param = new Object();
DynamicSum(stopwatch);
SumInt(stopwatch);
SumInt(stopwatch, param);
Sum(stopwatch);
DynamicSum(stopwatch);
SumInt(stopwatch);
SumInt(stopwatch, param);
Sum(stopwatch);
Console.ReadKey();
}
private static void Sum(Stopwatch stopwatch)
{
var sum = 0;
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < ITERATIONS; i++)
{
sum += i;
}
stopwatch.Stop();
Console.WriteLine(string.Format("Elapsed {0}", stopwatch.ElapsedMilliseconds));
}
private static void SumInt(Stopwatch stopwatch)
{
var sum = new Sum();
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < ITERATIONS; i++)
{
sum.intSum += i;
}
stopwatch.Stop();
Console.WriteLine(string.Format("Class Sum int Elapsed {0}", stopwatch.ElapsedMilliseconds));
}
private static void SumInt(Stopwatch stopwatch, dynamic param)
{
var sum = new Sum2();
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < ITERATIONS; i++)
{
sum.intSum += i;
}
stopwatch.Stop();
Console.WriteLine(string.Format("Class Sum int Elapsed {0} {1}", stopwatch.ElapsedMilliseconds, param.GetType()));
}
private static void DynamicSum(Stopwatch stopwatch)
{
var sum = new Sum();
stopwatch.Reset();
stopwatch.Start();
for (int i = 0; i < ITERATIONS; i++)
{
sum.DynSum += i;
}
stopwatch.Stop();
Console.WriteLine(String.Format("Dynamic Sum Elapsed {0}", stopwatch.ElapsedMilliseconds));
}
I've read dynamic makes the compiler run again, but what it does. Does it have to recompile whole method with the dynamic used as a parameter or rather those lines with dynamic behavior/context(?)
Here's the deal.
For every expression in your program that is of dynamic type, the compiler emits code that generates a single "dynamic call site object" that represents the operation. So, for example, if you have:
class C
{
void M()
{
dynamic d1 = whatever;
dynamic d2 = d1.Foo();
then the compiler will generate code that is morally like this. (The actual code is quite a bit more complex; this is simplified for presentation purposes.)
class C
{
static DynamicCallSite FooCallSite;
void M()
{
object d1 = whatever;
object d2;
if (FooCallSite == null) FooCallSite = new DynamicCallSite();
d2 = FooCallSite.DoInvocation("Foo", d1);
See how this works so far? We generate the call site once, no matter how many times you call M. The call site lives forever after you generate it once. The call site is an object that represents "there's going to be a dynamic call to Foo here".
OK, so now that you've got the call site, how does the invocation work?
The call site is part of the Dynamic Language Runtime. The DLR says "hmm, someone is attempting to do a dynamic invocation of a method foo on this here object. Do I know anything about that? No. Then I'd better find out."
The DLR then interrogates the object in d1 to see if it is anything special. Maybe it is a legacy COM object, or an Iron Python object, or an Iron Ruby object, or an IE DOM object. If it is not any of those then it must be an ordinary C# object.
This is the point where the compiler starts up again. There's no need for a lexer or parser, so the DLR starts up a special version of the C# compiler that just has the metadata analyzer, the semantic analyzer for expressions, and an emitter that emits Expression Trees instead of IL.
The metadata analyzer uses Reflection to determine the type of the object in d1, and then passes that to the semantic analyzer to ask what happens when such an object is invoked on method Foo. The overload resolution analyzer figures that out, and then builds an Expression Tree -- just as if you'd called Foo in an expression tree lambda -- that represents that call.
The C# compiler then passes that expression tree back to the DLR along with a cache policy. The policy is usually "the second time you see an object of this type, you can re-use this expression tree rather than calling me back again". The DLR then calls Compile on the expression tree, which invokes the expression-tree-to-IL compiler and spits out a block of dynamically-generated IL in a delegate.
The DLR then caches this delegate in a cache associated with the call site object.
Then it invokes the delegate, and the Foo call happens.
The second time you call M, we already have a call site. The DLR interrogates the object again, and if the object is the same type as it was last time, it fetches the delegate out of the cache and invokes it. If the object is of a different type then the cache misses, and the whole process starts over again; we do semantic analysis of the call and store the result in the cache.
This happens for every expression that involves dynamic. So for example if you have:
int x = d1.Foo() + d2;
then there are three dynamic calls sites. One for the dynamic call to Foo, one for the dynamic addition, and one for the dynamic conversion from dynamic to int. Each one has its own runtime analysis and its own cache of analysis results.
Make sense?
Update: Added precompiled and lazy-compiled benchmarks
Update 2: Turns out, I'm wrong. See Eric Lippert's post for a complete and correct answer. I'm leaving this here for the sake of the benchmark numbers
*Update 3: Added IL-Emitted and Lazy IL-Emitted benchmarks, based on Mark Gravell's answer to this question.
To my knowledge, use of the dynamic keyword does not cause any extra compilation at runtime in and of itself (though I imagine it could do so under specific circumstances, depending on what type of objects are backing your dynamic variables).
Regarding performance, dynamic does inherently introduce some overhead, but not nearly as much as you might think. For example, I just ran a benchmark that looks like this:
void Main()
{
Foo foo = new Foo();
var args = new object[0];
var method = typeof(Foo).GetMethod("DoSomething");
dynamic dfoo = foo;
var precompiled =
Expression.Lambda<Action>(
Expression.Call(Expression.Constant(foo), method))
.Compile();
var lazyCompiled = new Lazy<Action>(() =>
Expression.Lambda<Action>(
Expression.Call(Expression.Constant(foo), method))
.Compile(), false);
var wrapped = Wrap(method);
var lazyWrapped = new Lazy<Func<object, object[], object>>(() => Wrap(method), false);
var actions = new[]
{
new TimedAction("Direct", () =>
{
foo.DoSomething();
}),
new TimedAction("Dynamic", () =>
{
dfoo.DoSomething();
}),
new TimedAction("Reflection", () =>
{
method.Invoke(foo, args);
}),
new TimedAction("Precompiled", () =>
{
precompiled();
}),
new TimedAction("LazyCompiled", () =>
{
lazyCompiled.Value();
}),
new TimedAction("ILEmitted", () =>
{
wrapped(foo, null);
}),
new TimedAction("LazyILEmitted", () =>
{
lazyWrapped.Value(foo, null);
}),
};
TimeActions(1000000, actions);
}
class Foo{
public void DoSomething(){}
}
static Func<object, object[], object> Wrap(MethodInfo method)
{
var dm = new DynamicMethod(method.Name, typeof(object), new Type[] {
typeof(object), typeof(object[])
}, method.DeclaringType, true);
var il = dm.GetILGenerator();
if (!method.IsStatic)
{
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Unbox_Any, method.DeclaringType);
}
var parameters = method.GetParameters();
for (int i = 0; i < parameters.Length; i++)
{
il.Emit(OpCodes.Ldarg_1);
il.Emit(OpCodes.Ldc_I4, i);
il.Emit(OpCodes.Ldelem_Ref);
il.Emit(OpCodes.Unbox_Any, parameters[i].ParameterType);
}
il.EmitCall(method.IsStatic || method.DeclaringType.IsValueType ?
OpCodes.Call : OpCodes.Callvirt, method, null);
if (method.ReturnType == null || method.ReturnType == typeof(void))
{
il.Emit(OpCodes.Ldnull);
}
else if (method.ReturnType.IsValueType)
{
il.Emit(OpCodes.Box, method.ReturnType);
}
il.Emit(OpCodes.Ret);
return (Func<object, object[], object>)dm.CreateDelegate(typeof(Func<object, object[], object>));
}
As you can see from the code, I try to invoke a simple no-op method seven different ways:
Direct method call
Using dynamic
By reflection
Using an Action that got precompiled at runtime (thus excluding compilation time from the results).
Using an Action that gets compiled the first time it is needed, using a non-thread-safe Lazy variable (thus including compilation time)
Using a dynamically-generated method that gets created before the test.
Using a dynamically-generated method that gets lazily instantiated during the test.
Each gets called 1 million times in a simple loop. Here are the timing results:
Direct: 3.4248ms
Dynamic: 45.0728ms
Reflection: 888.4011ms
Precompiled: 21.9166ms
LazyCompiled: 30.2045ms
ILEmitted: 8.4918ms
LazyILEmitted: 14.3483ms
So while using the dynamic keyword takes an order of magnitude longer than calling the method directly, it still manages to complete the operation a million times in about 50 milliseconds, making it far faster than reflection. If the method we call were trying to do something intensive, like combining a few strings together or searching a collection for a value, those operations would likely far outweigh the difference between a direct call and a dynamic call.
Performance is just one of many good reasons not to use dynamic unnecessarily, but when you're dealing with truly dynamic data, it can provide advantages that far outweigh the disadvantages.
Update 4
Based on Johnbot's comment, I broke the Reflection area down into four separate tests:
new TimedAction("Reflection, find method", () =>
{
typeof(Foo).GetMethod("DoSomething").Invoke(foo, args);
}),
new TimedAction("Reflection, predetermined method", () =>
{
method.Invoke(foo, args);
}),
new TimedAction("Reflection, create a delegate", () =>
{
((Action)method.CreateDelegate(typeof(Action), foo)).Invoke();
}),
new TimedAction("Reflection, cached delegate", () =>
{
methodDelegate.Invoke();
}),
... and here are the benchmark results:
So if you can predetermine a specific method that you'll need to call a lot, invoking a cached delegate referring to that method is about as fast as calling the method itself. However, if you need to determine which method to call just as you're about to invoke it, creating a delegate for it is very expensive.