workflow window foundation =()=> - c#

What does = () => mean in c#?
I've used lambda's before but those empty parens () are throwing me off.
Familiar with this:
customers.Find(x=>x.FirstName=="John")
Article resource

It's assigning a lambda expression to the variable or property this.Implementation. You have to break down the operators like this:
this.Implementation
= //assignment operator
()=> new Sequence { /* stuff */ };
The () is to designate that the method takes no parameters; the => identifies what follows as the code to be run when the lambda is invoked.

The () simply means the anonymous method has no parameters. The way you're used to seeing, like customers.Find(x=>x.FirstName == "John") is the same... the first x is the parameter passed to the lambda. The parentheses are optional if there's only a single parameter, so this could also be written like this: customers.Find((x)=>x.FirstName == "John") With a method that takes no parameters, the 'single parameter' exclusion doesn't apply, so you have to write the (). You can see more in the documentation.
The = before the lambda call is assigning the method body that follows to the Implementation property.

This is known as a lambda expression. In essence, it's shorthand for defining a function.
Here is a decent tutorial explaining the concept:
http://www.dotnetperls.com/lambda

The () => new Sequence part along with the block below it is an lambda function that takes no parameters and return a Sequence
This lambda is assigned to this.Implementation so that at a later time you can call the lambda. E.g., var s = this.Implementation().

Related

string.Contains as a predicate not a function call?

I found this sample of code on SO (can't remember from where :/) that allowed me to check for line code arguments when launching my application :
if (e.Args.Length == 0 || e.Args.Any("-show".Contains))
{
//show interface...
}
I just can't seem to understand how the "-show".Contains works.
And if there's any difference with a (classic) x => x.Contains('"-show") (except for the evident typing gain).
Works like a charm but I'd like to understand why, I feel like something big is hapening.
This:
.Any("-show".Contains)
is basically shorthand for this:
.Any(s => "-show".Contains(s))
The Any method takes a delegate as a parameter and you can create that delegate in a number of ways. The first snippet uses a method group while the second uses a Lambda.
It's not really accurate to say that the first is shorthand for the second because method groups predate Lambdas, but if you think in terms of Lambdas when calling LINQ methods like Any then it is effectively the case.
As #jmcilhiney already said, it shorthand for:
.Any(s => "-show".Contains(s))
Contains is a function accepting 1 parameter which is of type string (and returns a boolean). Any() in this case wants a function that needs 1 param which is a string and that returns a boolean. So rather than adding an extra lambda warapper s=>, you can directly return .Contains
In technical terms this is a:
Func<string, boolean> //1 param string, output: boolean
Note that this code matches any argument that is a part of -show
thus either of the following arguments do match!
-show
-s
sh
ow
h
w
// etc..
Any() expects a Func<TSource, bool> delegate. So any function that returns a bool and takes an argument that is of the same type as the elements of the collection (string in your case) can be applied. This can be an existing function, or a lambda expression.
The signature of String.Contains is
bool Contains(string s)
That's why you can pass it to Any()
The equivalent would be x => "-show".Contains(x) rather than what you've shown.
After that you'll realise that all you're doing by introducing the x based lambda is to create a function accepting a single string argument and returning a bool and wrapping a function that accepts a single string and returns a bool. There's no need for the wrapper.

Is this proper way to pass parameters?

Reading this article I found one strange way to pass parameters to object:
_saveProductCommand = new RelayCommand(
param => SaveProduct(),
param => (CurrentProduct != null)
Is this typo or proper way to pass parameters?
What you are seeing is not something that applies to general properties, for example if the parameter was a string you would not be able to use the name => statement syntax.
If you look at the definition of RelayCommand you will see that the parameters are of type Action this is a special type that allows you to pass blocks of code or methods as objects, these are generally called Delegates.
The syntax you are referring to is called a Lambda and they come in a few forms.
The simplest is () => doSomething() in this case the lambda does not take any parameters and only calls the doSomething method.
The next is a lambda that takes a parameter param => doSomething(param) in this code the variable param is just a local variable for the code body of the lambda to be able to use, and the code that executes the lambda will need to pass something in, here is a more complete example;
var myLambda = param => doSomething(param);
myLambda("some string value");
So in this example the string will be passed to the doSomething method.
These examples have only covered lambdas that will convert down to the Action class, but you can also write a lambda that will give you a Func. There is also another form called Predicate this is essentially an Action that returns true or false;
I would suggest doing some additional reading on the Action class the Func class and the Predicate class.

Why can I assign incompatible lambda to Action?

I'm confused as to why this works:
Action myAction1 = () => myIntFunc();
...
private Int32 myIntFunc() {
return(4);
}
I would expect the compiler to not allow this because an Action represents functions that do not return parameters, yet myIntFunc clearly returns a parameter.
As further evidence, note that this does not work:
Action myAction2 = myIntFunc;
So it's like the lambda syntax is letting me get away with something I shouldn't be able to get away with. I'm guessing I'm overlooking something to do with how Actions and lambdas work together...??
I think its the same than when you do this:
myIntFunc();
Ignoring the result of the method.
What you're trying to do is explicitly allowed. Per the MSDN documentation on the Action delegate (emphasis added):
The encapsulated method must have no parameters and no return value. (In C#, the method must return void. […] It can also be a method that returns a value that is ignored.)
In the C# language specification, paragraph 6.5, one of the bullets says: If D has a void return type and the body of F is an expression, when each parameter of F is given the type of the corresponding parameter in D, the body of F is a valid expression (wrt §7) that would be permitted as a statement-expression (§8.6).
So it's OK to throw away the return value in that case.
For a method group conversion, see paragraph 6.6 instead. Then the method must be compatible including the return type.
So there's a difference between anonymous method (lambda) and normal (named) method (or method group).

What does () => {} mean?

I was reading Pulling the switch here and came across this code.
Can somoone please explain what is () => {} and what should I read up to understand that line of code?
var moveMap = new Dictionary<string, Action>()
{
{"Up", MoveUp},
{"Down", MoveDown},
{"Left", MoveLeft},
{"Right", MoveRight},
{"Combo", () => { MoveUp(); MoveUp(); MoveDown(); MoveDown(); }}
};
moveMap[move]();
It's a lambda expression:
All lambda expressions use the lambda operator =>, which is read as "goes to". The left side of the lambda operator specifies the input parameters (if any) and the right side holds the expression or statement block
Basically you are constructing a new, temporary function here that just calls a combination of two of the other functions.
As seen above, the () on the left side means that it has an empty parameter list (just like your other functions). The {} on the right means that it executes several statements inside a block, which makes it a "statement lambda" that is called for its side effects, in contrast to an "expression lambda", which computes a value.
() => {/*code*/} is a lambda expression, a convenient way to create an anonymous delegate that takes zero parameters. Essentially it creates a callable piece of code that in your case moves up twice and then moves down twice.
You are not limited to lambdas without parameters - you can create ones with arguments:
Action<string> callable = (name) => {Console.WriteLine("Hello, {0}!", s);};
callable("world");
callable("quick brown fox");
It's a lambda expression. MSDN refers to it as a "statement lambda":
A statement lambda resembles an expression lambda except that the
statement(s) is enclosed in braces.
The dictionary contains a set of Actions (delegates). 4 are explicitly defined, and the 5th is an anonymous function which calls 2 of the others. The last line of code invokes an Action (it retrieves the delegate from the dictionary by key and invokes it).
() this is anonymous function with No parameters
=> is lambda operator (pronounce as Goes to )
Dictionary has been initialized with KeyValuePair, Last option is an anonymous function which takes no parameter and invoke other functions

Why can I use a lambda expression in place of a callback delegate?

I discovered some new C# syntax and do not understand what it means. Here is the syntax-related code:
1)
BeginInvoke(new Action(() =>
{
PopulateUI(ds);
}));
2)
private void OnFormLoad()
{
ThreadPool.QueueUserWorkItem(() => GetSqlData());
}
What is the meaning of new Action() and what is the meaning of the => symbol?
The syntax of ThreadPool.QueueUserWorkItem was ThreadPool.QueueUserWorkItem(new WaitCallback(PrintOut), "Hello"); but here it shows ThreadPool.QueueUserWorkItem(() => GetSqlData());, so how does it work? Why is WaitCallback missing? Please explain in detail.
Thanks a lot.
Have a look at
Action Delegate
Encapsulates a method that has a
single parameter and does not return a
value. You can use the Action
delegate to pass a method as a
parameter without explicitly declaring
a custom delegate.
and
and Lambda Expressions (C# Programming Guide)
A lambda expression is an anonymous
function that can contain expressions
and statements, and can be used to
create delegates or expression tree
types.
All lambda expressions use the lambda
operator =>, which is read as "goes
to". The left side of the lambda
operator specifies the input
parameters (if any) and the right side
holds the expression or statement
block. The lambda expression x => x *
x is read "x goes to x times x."
As others have said, it is a lambda, which is basically an anonymous (unnamed) local function.
This might make a bit more sense if you look at some similar code that doesn't use lambdas:
// With a lambda
private void OnFormLoad()
{
ThreadPool.QueueUserWorkItem(() => GetSqlData());
}
// Without a lambda
private void OnFormLoad()
{
ThreadPool.QueueUserWorkItem(ExecuteGetSqlData);
}
private void ExecuteGetSqlData()
{
// If GetSqlData returns something, change this to "return GetSqlData();"
GetSqlData();
}
As for the other code, normally you shouldn't have to do new Action. The problem is that the BeginInvoke method takes a Delegate, which is sort of old school, and breaks how most new code works.
With newer code (that takes something like Action, or a specific type of delegate, like WaitCallback), you either write a lambda, or simply give the name of a function inside your class. The example code I wrote above demonstrates both of these.
Also note that if you see something like: (Action) (() => Blah()), it is pretty much the same as new Action(() => Blah()).
These are known as lambda expressions, which aren't very different from delegates in C#.
The empty () mean there are no arguments, and what's between the (optional) {} are the lambda expression bodies. The => operator simply associates both expressions together to make a lambda expression. As an aside, they're commonly found in LINQ code.
There's nothing special about new Action(), just that it's a delegate that can map a lambda expression to itself.
As for ThreadPool.QueueUserWorkItem(), the WaitCallback argument is a delegate. You can either pass the name of a named delegate as the argument, pass an anonymous delegate object or write a lambda expression for this anonymous delegate (in your case it's () => GetSqlData()).
Lambda expression
Action Delegate

Categories