Arguments passed "by name" in C# - c#

The Scala programming language has a neat feature, called pass by name arguments, that allows some arguments to only be evaluated if required.
For example, it's possible to write a while loop using a curried method such as the following:
// This is Scala code. A simulated while loop
#scala.annotation.tailrec
def myWhile(condition: => Boolean)(actions: => Unit): Unit = {
if(condition) {
actions
myWhile(condition)(actions)
}
}
This method can be used like a regular while loop, thanks to Scala's syntactic sugar, closures and—of particular interest here—the ability to pass expressions as function arguments, which are evaluated when referenced (as indicated by the : => type argument declaration).
For example, the following prints "Hello!" to the console ten times:
var i = 0
myWhile(i < 10) {
println("Hello!")
i += 1
}
For those who need to understand what is happening, the expression i < 10 is evaluated each time condition appears inside the if(...) statement inside the method, similarly, println("Hello!"); i += 1 is evaluated each time actions appears in the body of the method. When recursively calling myWhile for the next iteration, the expressions are passed as is, since the method requires expressions, not values. Scala terms these pass by name arguments.
If these arguments were passed by value instead, then i < 10 would be passed to myWhile as false, while "Hello!" would be printed exactly once, i would be incremented once, and the loop would execute infinitely.
(Scala is primarily a functional language, and this code is not even close to being FP, but it's a simple example.)
My question is, is there a way to pass arguments in this way to a C# function? Also note that I'm restricted to using C# 7.3. :-(

It sounds like you can get somewhat close with Func`1 and Action:
void MyWhile(Func<bool> condition, Action action) {
while (condition()) {
action();
}
}
and calling as:
int i = 0;
MyWhile(() => i < 10, () => {
Console.WriteLine("Hello!");
++i;
});
The syntax is a bit different, but the idea is similar.

Related

Anonym functions only benefit against lambdas

I am still reading documentation about C# and I fell on anonymous functions.
It is true that they prioritize lambda expressions against it but,
they also said right after :
There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list. This means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions.
This (quotation) is what I want to understand with some few examples if needed. Thank you.
If you ignore the parameters in a delegate then with anonymous function syntax using delegate you can leave them out:
Action<int> a = delegate { Console.WriteLine("I am ignoring the int parameter."); }; //takes 1 argument, but not specified on the RHS
a(2); // Prints "I am ignoring the int parameter."
There is no way of doing this with lambda expressions:
Action<int> a = => { Console.WriteLine("I am ignoring the int parameter."); }; // syntax error
Action<int> a = () => { Console.WriteLine("I am ignoring the int parameter."); }; // CS1593 Delegate 'Action<int>' does not take 0 arguments
It's not terribly useful, but it can be a bit handy when you know you want something done on an event and don't even care what it's signature is.
button.OnClick += delegate { Console.WriteLine("Button clicked and that's all I care about"); };
Historically the big advantage anonymous functions had in C# 2.0 was that they existed. Lambda syntax didn't get introduced until C# 3.0.

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.

Advice on lambda expression [duplicate]

This question already has answers here:
Where do I use delegates? [closed]
(8 answers)
Closed 7 years ago.
Say that I have this line of code:
Action<int> square = number => Console.WriteLine(number * number);
Though I understand that it is handy to create a method on the fly, if you only need to call the lamda expression once, does it gain any perfomance by doing so?
In addition, let's say I do something more with the value before the WriteLine:
Action<int> square = number => {
number += 10;
Console.WriteLine(number * number);
};
I could just solve this very simple by adding 10 to number and then do number * number without the lambda expression. Can anyone give me a good example/situation when to use this expression?
I understand that it is handy to create a method on the fly, using lambda, if you only need to call it once but do I gain any perfomance by doing so?
Delegates (such as instances of Action<T>) are one level of indirection (very similar to virtual method dispatch); the runtime does not just execute the code inside the method when you invoke the delegate; the runtime will first have to figure out what method they reference, then invoke that method.
Delegates certainly don't speed things up. But then you should state what we are comparing them against.
That being said, the minute overhead of delegate dispatch is generally negligible in all but the most extreme scenarios; don't worry too much about the performance of delegate invocation.
Action<int> square = number =>
{
number += 10;
Console.WriteLine(number * number);
};
Can anyone give me a good example/situation when to use this expression?
I would not mutate arguments if I could just as well write the code another way; all the more so when we are talking about a lambda's parameter. I would instead put the value derived from the argument into a (temporary) local variable:
Action<int> square = number =>
{
int n = number + 10;
Console.WriteLine(n * n);
};
The code is not really any longer, and generally easier to understand because you don't have to worry about your lambda accidentally changing an object passed to it.
Imagine the following:
You have list of values where you want to apply a function. You can save this function in an Action and later apply this function in your code.
E.g:
Predicate<int> isEven = number => number % 2 == 0;
List<int> numbers = Enumerable.Range(1,100);
var evenNumbers = numbers.Where(isEven);
This is more reusable and more readable than a foreach loop.

Why do parentheses around lambda statement cause syntax error?

I'm looking for a good explanation why one piece of code fails to compile and the other compiles just fine.
Fails:
richTextBox1.Invoke(new MethodInvoker((() => { richTextBox1.AppendText("test"); })));
Gives the error
Method name expected
on the opening parenthesis right after MethodInvoker(. Apparently, I can't wrap my lambda statements in parentheses.
Compiles:
richTextBox1.Invoke(new MethodInvoker(() => { richTextBox1.AppendText("test"); }));
The questions is - why?
I always took it for granted that I could wrap any method param in parentheses if I wanted but apparently that's not the case with lambda expressions. I understand that they are somewhat special, but I still can't see a good reason for this. Maybe I don't understand something about the syntax. I would really like to get it.
By the way, this presents in VS2008, .NET 3.5 SP1, I haven't tested it in VS2010 and .NET 4 yet.
It's not a lambda expression, it's a parenthesized expression that contains a lambda expression. Therefore, the node for this parameter in the abstract syntax tree for this method invocation would be a parenthesized expression, and not a lambda expression as required by the specification. This is why.
There are other places where the Microsoft C# compiler does violate the specification and accept such an expression even though it shouldn't (per the specification) but this is not one of them.
The relevant section of the specification is §6.5.
You are mistaken in the premise that you have written a “method param”. The construct you have created is not a method call, you have written a delegate creation expression (see the C# specification, section 7.6.10.5), which is supposed to have a single argument, which must be either
a method group,
an anonymous function or
a value of either the compile time type dynamic or a delegate-type.
In your case, it is not a method group (the error message is hinting that a method name is expected there), nor an anonymous function (since it is an expression which “somewhere inside” contains an anonymous function), nor a value of the said types.
If you wrote a method invokation, you could, indeed, wrap the parameter in parentheses, even if it contains a lambda expression:
void Method(Action action)
{
}
...
Method((() => { Console.WriteLine("OK"); }));
Because the compiler expects ()=>{} inside the Invoke() method and in the first example it does not find it. Everything within the parenthesis is evaluated first returning a single object, at which case the compiler expects the reference to a delegate.
Edited
I have solved the same problem with this Extension method:
public delegate void EmptyHandler();
public static void SafeCall(this Control control, EmptyHandler method)
{
if (control.InvokeRequired)
{
control.Invoke(method);
}
else
{
method();
}
}
So you can call
RichTextBox rtb = new RichRextBox();
...
rtb.SafeCall( ()=> rtb.AppendText("test") );

Functors when should I use them whats their intended use [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
I Just can't seem to wrap my head around them.
As I understand it's dynamically adding logic to a class. Are classes within the framework prepared for this?
Why should I just extend the class and add the functionality to it in the extension. I would be globally accessible and afaik much easier to maintain.
I've Read there are 4 functor types:
Comparer
Closure
Predicate
Transformer
We should probably Handle each one of them.
p.s. is there something like it in vb?
So I can state I think that lambda expressions are functors. This clears up things for me a bit :) (hehe)
Lambda expressions are functors?
Anonymous functions are functors?
But I asked this question because I ran into another type of fucntors namely these ones:
delegate void FunctorDelegate(int value);
class Addition {
FunctorDelegate _delegate;
public Addition AddDelegate(FunctorDelegate deleg) {
_delegate += deleg;
return this;
}
public int AddAllElements(IList< int> list) {
int runningTotal = 0;
foreach( int value in list) {
runningTotal += value;
_delegate(value);
}
return runningTotal;
}
}
And then calling it with this:
int runningTotal = new Addition()
.AddDelegate(new FunctorDelegate(
delegate(int value) {
if ((value % 2) == 1) {
runningOddTotal += value;
}
}))
.AddDelegate(new FunctorDelegate(
delegate(int value) {
if ((value % 2) == 0) {
runningEvenTotal += value;
}
}))
.AddAllElements(list);
So no fancy lambda style things.
Now I have this example but it isn't at all clear why this is a "good" solution.
Are delegates (functors) used as lambda expressions or anonymous methods "in most cases" just there as a shortcut for the programmer? There are as far as I can see only a few cases where they're actually the prefered choice for a problem.
I think you're confusing terms from different languages. You seem to be using "Functor" in the C++ or Java sense, e.g. see the wikipedia page. In C++, it's an object of a class that overloads the function-call operator, so it can be used as a function but with state.
This is logically the same thing as a delegate bound to an instance method in C# (or any .NET language).
There are three ways to write such a thing. First, you can write an ordinary method, and then assign the name of the method to a delegate variable.
void MyMethod() { Console.WriteLine("Hi!"); }
void Foo()
{
Action a = MyMethod;
a();
}
Second, you can use anonymous method syntax, introduced in C# 2.0:
void Foo()
{
Action a = delegate { Console.WriteLine("Hi!"); }
a();
}
Thirdly, you can use lambda syntax, introduced in C# 3.0:
void Foo()
{
Action a = () => Console.WriteLine("Hi!");
a();
}
The advantage of the last two is that the body of the method can read and write local variables in the containing method.
The advantage of lambda syntax over anon-methods are that it is more succinct and it does type inference on parameters.
Update: The advantage of anon-methods (delegate keyword) over lambdas is that you can omit the parameters altogether if you don't need them:
// correct way using lambda
button.Click += (sender, eventArgs) => MessageBox.Show("Clicked!");
// compile error - wrong number of arguments
button.Click += () => MessageBox.Show("Clicked!");
// anon method, omitting arguments, works fine
button.Click += delegate { MessageBox.Show("Clicked!"); };
I know of only one situation where this is worth knowing, which is when initializing an event so that you don't have to check for null before firing it:
event EventHandler Birthday = delegate { };
Avoids a lot of nonsense elsewhere.
Finally, you mention that there are four kinds of functor. In fact there are an infinity of possibly delegate types, although some authors may have their favourites and there obviously will be some common patterns. An Action or Command takes no parameters and returns void, and a predicate takes an instance of some type and returns true or false.
In C# 3.0, you can whip up a delegate with up to four parameters of any types you like:
Func<string, int, double> f; // takes a string and an in, returns a double
Re: Updated Question
You ask (I think) if there are many use cases for lambdas. There are more than can possibly be listed!
You most often see them in the middle of larger expressions that operate on sequences (lists computed on-the-fly). Suppose I have a list of people, and I want a list of people exactly forty years old:
var exactlyForty = people.Where(person => person.Age == 40);
The Where method is an extension method on the IEnumerable<T> interface, where T in this case is some kind of Person class.
This is known in .NET as "Linq to Objects", but known elsewhere as pure functional programming on sequences or streams or "lazy" lists (all different names for the same thing).
In .NET terms, I think what you are describing is the Delegate - and it exists in all of .NET, not just C#.
I'm not sure that a "closure" would a "type" in the same was as a comparer/predicate/transformer, since in C# terms a closure is simply an implementation detail but can be any of those three.
In .NET, delegates are used in two main ways:
as the eventing mechanism
to provide functional-style programming
The first is important, but it sounds like you are more interested in the second. In reality, they operate much like single-method interfaces... consider:
List<int> vals = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
List<int> evenVals = vals.FindAll(i => i % 2 == 0); // predicate
List<string> valsAsStrings = vals.ConvertAll(i => i.ToString()); // transformer
// sort descending
vals.Sort((x, y) => y.CompareTo(x)); // comparer
A closure is more where we bring additional scope from outside the delegate into the delegate:
int max = int.Parse(Console.ReadLine()); // perhaps 6
List<int> limited = vals.FindAll(i => i <= max);
here the max is captured into the delegate as a closure.
Re "Are classes within the framework prepaired for this?" - many are, and LINQ goes a long way to allowing this even wider. LINQ provides extension methods over (for example) all of IEnumerable<T> - meaning that collections without delegate-based access aquire them for free:
int[] data = { 1,2,3,4,5,6,7,8,9 };
var oddData = data.Where( i => i % 2 == 1 );
var descending = data.OrderBy(i => -i);
var asStrings = data.Select(i => i.ToString());
Here the Where and OrderBy methods are LINQ extension methods that take delegates.
Interesting with terminology; my spontaneous interpretation of the term "Functor" was that it referred to anonymous methods. So that will be my take on it.
These are some of my typical uses:
Comparisons (usually for sorting a list):
List<int> ints = new List<int>();
ints.AddRange(new int[] { 9, 5, 7, 4, 3, 5, 3 });
ints.Sort(new Comparison<int>(delegate(int x, int y)
{
return x.CompareTo(y);
}));
// yes I am aware the ints.Sort() would yield the same result, but hey, it's just
// a conceptual code sample ;o)
// and the shorter .NET 3.5 version:
ints.Sort((x, y) =>
{
return x.CompareTo(y);
});
I will use this approach for comparisons, rather than having it in its own method an using a delegate for that method, in the cases where this particular sort happens in one place only. If it is likely that I will want to use the same comparison somewhere else, it gets to live in its own, reusable method.
Another of my fairly common uses is in unit testing, when the test relies on some event being raised. I have found that to be essential when unit testing workflows in Workflow Foundation:
WorkflowRuntime runtime = WorkflowHost.Runtime;
WorkflowInstance instance = runtime.CreateWorkflow(typeof(CreateFile));
EventHandler<WorkflowEventArgs> WorkflowIdledHandler = delegate(object sender, WorkflowEventArgs e)
{
// get the ICreateFileService instance from the runtime
ISomeWorkflowService service = WorkflowHost.Runtime.GetService<ISomeWorkflowService>();
// set the desired file content
service.DoSomeWork(instance.InstanceId, inputData);
};
// attach event handler
runtime.WorkflowIdled += WorkflowIdledHandler;
instance.Start();
// perform the test, and then detach the event handler
runtime.WorkflowIdled -= WorkflowIdledHandler;
In this case it is simpler to have the event handler declared as anonymous methods since it uses the instance variable that is defined in the unit test method scope. Had I intstead opted to implelment the event handler as its own separate method I would also need to figure out a way for it to pick up instance, probably by introducing a class level member, which would not seem like a perfect design in a unit test class.
There are more cases where I find this in my code, but they usually have one or two things in common:
I have no interest in referencing that piece of code from anywhere else than in that particular place.
The method needs access to data that would be out of the scope for a regular method
The real answer is that a functor is a type of mathematical object, and is "reified" by different languages in different ways. For example, suppose that you have a "container" object that stores a bunch of other objects of the same type. (For example, a set or array) Then, if your language had a method that let you 'map' over the container, so that you could call a method on each object in the container, then the container would be a functor.
In other words, a functor is a container with a method that lets you pass a method to its contained things.
Every language has its own way of doing this, and they sometimes conflate the usage. For example, C++ uses function pointers to represent the "passing in" of a method, and calls the function pointer a "functor." Delegates are just a handle on methods that you can pass in. You are using the terminology "incorrectly", just like C++ does.
Haskell gets it right. You declare that a type implements the functor interface, and then you get the mapping method.
Functions (like lambdas) are functors too, but it can be kind of hard to think of a function as a "container". In short, a function is a "container" around a return value, constructed in such a way that the return value (possibly) depends on the function's arguments.
I'm sure you mean Lambda Expressions. Those are Small Functions you can write very quickly, and they have the characteristic "=>" Operator. These are a new Feature of C# 3.0.
This Example will be a classic Transformer; to use one we need a delegate to define the signature for the Lambda Function.
delegate int Transformer(int i);
Now Declare a Lambda with this delegate:
Transformer sqr = x => x * x;
We can use it like a normal function:
Console.WriteLine(sqr(3)); //9
These are used in LINQ Queries a lot, for example to Sort (Comparer), to Search through (Predicate).
The book "C# Pocket Reference" (apart from beign the best around in my opinion, has a very good part on Lambdas. (ISBN 978-0-596-51922-3 )

Categories