Func Delegate

Ronald Rex 1,666 Reputation points
2023-08-14T14:23:52.6433333+00:00

Hi Friends. I'm struggling with trying to understand this code below. Not sure why str is assingned to selector. Very confusing how this is written selector = str => str.ToUpper(); is selector the name of the delegate or is that a variable? Is str a method or variable? Please if I could get some help to understand this very confusing syntax. Does whats to the left of the => go to str.ToUpper();? And great articles on Delegates and Delegate Even Handlers?

// Declare a Func variable and assign a lambda expression to the
// variable. The method takes a string and converts it to uppercase.
Func<string, string> selector = str => str.ToUpper();

// Create an array of strings.
string[] words = { "orange", "apple", "Article", "elephant" };
// Query the array and select strings according to the selector method.
IEnumerable<String> aWords = words.Select(selector);

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,399 questions
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 121.3K Reputation points
    2023-08-14T15:21:32.1733333+00:00

    I do not think that str is assigned to selector. The whole “str => str.ToUpper()” is assigned:

    Func<string, string> selector = ( str => str.ToUpper() );
    

    where “str => str.ToUpper()” is a short form of a function that looks like this:

    string MyFunction( string str )
    {
       return str.ToUpper();
    }
    

    Your anonymous compact form is added to selector.

    Therefore, str is the name of function parameter.

    To get the results, use something like this: string[] result = aWords.ToArray( ). Your function will be executed sequentially for all of items.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.