Using Func<T> parameters - c#

I have a Func in my code that's declared like this:
Func<string, int, bool> Filter { get; set; }
How can I reach the string and the int variables that are parameters of the Func in order to use them in my code?

The parameters only exist when the function is called... and they're only available within the function. So for example:
foo.Filter = (text, length) => text.Length > length;
bool longer = foo.Filter("yes this is long", 5);
Here, the value "yes this is long" is the value of the text parameter while the delegate is executing and likewise the value 5 is the value of the length parameter while it's executing. At other times, it's a meaningless concept.
What are you really trying to achieve? If you could give us more context, we could almost certainly help you better.

You could use an anonymous method:
Filter = (string s, int i) => {
// use s and i here and return a boolean
};
or a standard method:
public bool Foo(string s, int i)
{
// use s and i here and return a boolean
}
and then you could assign the Filter property to this method:
Filter = Foo;

See this sample here - http://www.dotnetperls.com/func
using System;
class Program
{
static void Main()
{
//
// Create a Func instance that has one parameter and one return value.
// ... Parameter is an integer, result value is a string.
//
Func<int, string> func1 = (x) => string.Format("string = {0}", x);
//
// Func instance with two parameters and one result.
// ... Receives bool and int, returns string.
//
Func<bool, int, string> func2 = (b, x) =>
string.Format("string = {0} and {1}", b, x);
//
// Func instance that has no parameters and one result value.
//
Func<double> func3 = () => Math.PI / 2;
//
// Call the Invoke instance method on the anonymous functions.
//
Console.WriteLine(func1.Invoke(5));
Console.WriteLine(func2.Invoke(true, 10));
Console.WriteLine(func3.Invoke());
}
}

Related

Why can't you invoke the fuction directly with the parameters with Func?

I just have a question about the Func and Action delegate.
I just wonder why you can't do this directly:
public static int addTowNumber(int a, int b)
{
return a + b;
}
Func<int, int, int> add = addTowNumber(1,2);
But you have to do this:
Func<int, int, int> add = addTowNumber;
var addNumber = add(1, 2);
Console.WriteLine(addNumber);
By passing the arguments you are actually invoking the method, and returning an int.
To store a reference to a function, to be invoked later, you don't pass the arguments, which is why this is correct:
Func<int, int, int> add = addTowNumber;
You can then provide any arguments you like when invoking:
int result1 = add(1, 2);
int result2 = add(3, 4);
If you want to defer execution of a method with predefined arguments, which is what it appears you are trying to do, you need to create a closure like this:
Func<int> add = () => addTowNumber(1, 2);
int result = add();

Can't pass delegate

I've created a function that gets console input from the user as-long as it fits a filter so to speak.
public delegate TResult OutFunc<in T, TValue, out TResult>(T arg1, out TValue arg2);
public static T PromptForInput<T>(string prompt, OutFunc<string, T, bool> filter)
{
T value;
do { Console.Write(prompt); }
while (!filter(Console.ReadLine(), out value));
return value;
}
This works great when I call the method as I do below. which gets a number from the user as long as it parses to an int which is in the range of (0-10).
int num = PromptForInput("Please input an integer: ",
delegate(string st, out int result)
{ return int.TryParse(st, out result) && result <= 10 && result >= 0; } );
I want to be able to re-use common filters. In multiple places in my program I want to get an int input from the user, so I've separated out the logic for that, and put that in its own function.
private bool IntFilter(string st, out int result)
{
return int.TryParse(st, out result) && result <= 10 && result >= 0;
}
Now I get an error when I attempt to do this:
int num = PromptForInput("Please input an integer: ", IntFilter);
The type arguments for method 'PromptForInput(string, OutFunc)' cannot be inferred from the usage. Try specifying the type arguments explicitly.
How can I explicitly specify the type arguments in this case?
You have a generic function, and so need to declare the type:
int num = PromptForInput<int>("Please input an integer: ", IntFilter);
The compiler is just saying it can't figure that out on it's own and needs it declared explicitly.
Thanks to LordTakkera's answer I was able to also find this works as-well
int num = PromptForInput("Please input an integer: ", new OutFunc<string, int, bool>(IntFilter));
The compiler actually does this implicitly when compiling as long as you explicitly specify PromptForInput<int>. Though, I don't understand why the compiler can't figure this out implicitly.

C# Func<> and extension methods question

I have seen someone write below kind of Func<> pattern. And I am trying to experiment with Funcs and Lambdas to get the concepts right.
so ExperimentalSelect returns a Func (with 2 args and bool return value).
But I fail to understand that how all of the 3 return statements are valid (1 at a time).
public static Func<BinaryTreeNode<int>, int, bool> nodeSelector = (x, y) =>
{
return x.Value > y;
};
public static Func<int, int, bool> intSelector = (x, y) =>
{
return x > y;
};
public static Func<BinaryTreeNode<int>, int, bool> ExperimentalSelect (int number)
{
return nodeSelector; // seems straightforward, i agree this should work
// how does this work ? intSelector is different type Func<>
// and it is executing it here, thereby returning the bool type result
// and not Func<> type as the return type of this method should
return (x, y) => intSelector(number, number);
// and how does this work ? what is node here ?
// and SomeMethod returns bool and not Func<> type
return (node, x) => SomeMethod(node, number, true);
}
private static bool SomeMethod(BinaryTreeNode<int> node, int someNumber,
bool doSomething)
{
return node.Value < someNumber;
}
EDIT:
If an ext. method expects a func
IEnumerable<int> selected = tree.TakeWhile(ExperimentalSelect);
How does SomeMethod work here ?, it is not a Func<> !
What does this syntax mean: (node, x) => SomeMethod(node, number, true);
Where is the node or x in picture here ?
Your comments above the returns are not correct.
intSelector and SomeMethod are not executed there. They will only be executed, when the return value of ExperimentalSelect is executed.
return (x, y) => intSelector(number, number);
This defines an anonymous method with two parameters. One of type BinaryTreeNode<int> and one of type int and a return value of bool, because that's what's the return type of ExperimentalSelect. The body of this anonymous method is the call to intSelector which is executed only, when the anonymous method itself is executed. This means, the body of this anonymous method can be anything you wish. It can even be multiple statements:
return (x, y) => {
var temp;
temp = y;
y = x;
x = temp;
return intSelector(number, y);
}
The anonymous method then is returned and not the result of executing it.
Your return statement is equivalent to the following:
Func<BinaryTreeNode<int>, int, bool> result =
(x, y) => intSelector(number, number);
return result;
You can verify this yourself with your debugger. Add a break point inside intSelector and step over the return statement. You will see, the breakpoint will not be hit.
One important point is the following:
Func can be seen as a pointer to a function.
Func<BinaryTreeNode<int>, int, bool> result =
(x, y) => SomeMethod(x, number, true);
This will create an anonymous method and result will point to that anonymous method.
However, have a look at the following code:
Func<BinaryTreeNode<int>, int, bool, bool> result = SomeMethod;
In this case, result will directly point to SomeMethod. No anonymous method is created here. Note the difference in the type of result. Because the first code only executes SomeMethod in the body of the anonymous method, the type of result doesn't need to match the signature of SomeMethod. But in the second code, you directly assign SomeMethod to result and thus the type of result must match the signature of SomeMethod.
More:
Look at the following code:
public static Func<BinaryTreeNode<int>, int, bool> ExperimentalSelect (int number)
{
return (x, y) => intSelector(number, number);
}
Func<BinaryTreeNode<int>, int, bool> result = ExperimentalSelect(10);
Console.WriteLine(result(30, 20)); // writes false
It will print false, although 30 is bigger than 20. Why?
The reason is, that your anonymous method has x and y as input parameters, but they are not used anywhere in its body. Instead, you pass number as both parameters to intSelector. The value of number is 10, and 10 isn't greater than 10.
The correct way to write this code would be like this:
public static Func<BinaryTreeNode<int>, int, bool> ExperimentalSelect ()
{
return (x, y) => intSelector(x, y);
}
Func<BinaryTreeNode<int>, int, bool> result = ExperimentalSelect();
Console.WriteLine(result(30, 20)); // writes true
As you can see, I now pass x and y to intSelector. I also removed the parameter number from ExperimentalSelect, because it is not used anywhere.
Ask yourself - are these two lines of code also correct:
Func<BinaryTreeNode<int>, int, bool> a =
(x, y) => intSelector(number, number);
Func<BinaryTreeNode<int>, int, bool> b =
(node, x) => SomeMethod(node, number, true);
The answer - yes. As it is for the return statements in your code.
I think perhaps you're either slightly misunderstanding the syntax or perhaps not understanding exactly what a Func is (apologies if either is not the case).
You seem to think that in this case
return (x, y) => intSelector(number, number);
what gets returned is the intSelector(number, number) part. But in reality the whole thing after return keyword is a return value. You can rewrite it like this:
return (BinaryTreeNode<int> x, int y) => intSelector(number,number);
which is roughly equivalent to returning an anonymous delegate with two parameters of type BinaryTreeNode<int> and int which returns the value of type bool. So it's your Func<BinaryTreeNode<int>, int, bool> right there.
Basically, the part to the left of => describes arguments and the part to the right is the method body, and the return type of the whole thing is the return type of the body.
Take a look at Lambda Expressions article by Eric White, it'll make sense to you.

Is there a way to cast a function

I think it would greatly simplify function overloading if I could just write the case that takes the most parameters and then simply stuff each case having less parameters with dummy params. For example..
// Add two integers
Func<int, int, int> addInts = (x, y) => { return x + y; };
// Add one to an integer
Func<int, int> addOne = (x) => { return x++; };
// In this case Func takes 2 args and has 1 return
public int IntCalc(Func<int,int,int> operation, int param1, int param2)
{
return operation(param1, param2);
}
// In this case Func takes 1 arg and has 1 return
public int IntCalc(Func<int, int> operation, int param1, int param2)
{
// This cast would allow me to do the overload
Func<int, int, int> castedOperation = (Func<int, int, int>)addOne;
return IntCalc(castedOperation, param1, 0);
}
So is there a way to do this? Is this a horrible practice?
You can only cast if the parameter signatures are compatible. In your case you'd need to define a lamda since converting a function with one parameter to a function with two parameters makes no sense in general.
Func<int, int, int> castedOperation = (i1,i2)=>addOne(i1);
If it's good practice depends on the contract of how the delegate will be used. If your functions with less parameters can fulfill that contract then this lamda based conversion is perfectly fine.
As a sidenode your addOne function is really ugly. While the increment of x has no effect because the parameter gets copied and thus only the copy is incremented and discared, implementing it as return x+1; would be much nicer than return x++; since you don't actually want to modify x.
Apart from the accepted answer you should also change the addOne to operation. So complete function would be
// In this case Func takes 1 arg and has 1 return
public int IntCalc(Func<int, int> operation, int param1, int param2)
{
// This cast would allow me to do the overload
Func<int, int, int> castedOperation = (i1,i2)=>operation(i1);
return IntCalc(castedOperation, param1, 0);
}
If your all parameters are the same type you can use params
adder(bool sample, params int[] a)
{
....
}
adder(2,3,4);
also you can use Named Parameter in C# 4.0.
Your approach is useful in constructors (you can do this with them).

Scope of variables inside anonymous functions in C#

I have a doubt in scope of varibles inside anonymous functions in C#.
Consider the program below:
delegate void OtherDel(int x);
public static void Main()
{
OtherDel del2;
{
int y = 4;
del2 = delegate
{
Console.WriteLine("{0}", y);//Is y out of scope
};
}
del2();
}
My VS2008 IDE gives the following errors:
[Practice is a class inside namespace Practice]
1.error CS1643: Not all code paths return a value in anonymous method of type 'Practice.Practice.OtherDel'
2.error CS1593: Delegate 'OtherDel' does not take '0' arguments.
It is told in a book: Illustrated C# 2008(Page 373) that the int variable y is inside the scope of del2 definition.
Then why these errors.
Two problem;
you aren't passing anything into your del2() invoke, but it (OtherDel) takes an integer that you don't use - you still need to supply it, though (anonymous methods silently let you not declare the params if you don't use them - they still exist, though - your method is essentially the same as del2 = delegate(int notUsed) {...})
the delegate (OtherDel) must return an int - your method doesn't
The scoping is fine.
The error has nothing to do with scopes. Your delegate must return an integer value and take an integer value as parameter:
del2 = someInt =>
{
Console.WriteLine("{0}", y);
return 17;
};
int result = del2(5);
So your code might look like this:
delegate int OtherDel(int x);
public static void Main()
{
int y = 4;
OtherDel del = x =>
{
Console.WriteLine("{0}", x);
return x;
};
int result = del(y);
}

Categories

Resources