Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Func<> with lambda expression

Tags:

c#

lambda

I have found following part of code in some examples while learning Func<> syntax:

  public static class Lambda
    {
        public static int MyFunc(Func<string, int> func)
        {
            //some logic
            return 0;
        }
    }

And sample call :

var getInt = Lambda.MyFunc((url) => { Console.WriteLine(url); return 0; }

And My Question :

Why passing above func as lambda expression with this (url) is allowed if value is never assigned ( or maybe is ?)? What is the point of passing Func like this ?

Edit : To clarify my question . I was only wondering about this sample call - why passing string as argument like above (using lambda (url) => {} ) is not forbidden by compiler if the value can not be initiated. Is there any example that can be useful with passing string like above ?

like image 269
Radek Avatar asked Jul 20 '15 21:07

Radek


1 Answers

url is the name of the parameter for the lambda expression. It's like writing a method like this:

public static int Foo(string url)
{
    Console.WriteLine(url);
    return 0;
}

Then creating a delegate from it:

Func<string, int> func = Foo;

Now in order to call the delegate, you need to provide it a string - and that then becomes the value of the parameter, just like if you called the method normally:

int result = func("some url");
like image 88
Jon Skeet Avatar answered Oct 11 '22 13:10

Jon Skeet