CS计算机代考程序代写 c# C# Classes

C# Classes

C# Programming

Quincy College

Fall 2021

Robert I. Pitts

 Processing array elements with methods

 Lambda expressions

 Delegates

Fall 2021C# Programming 2

 Array class has static functions run on array
of any type
int[] scores = …;

int[] certainScores =

Array.FindAll(scores, predicate);

 Predicate: function that returns Boolean value
bool PredicateName(ElementType val)

{

// return true/false based on val

}

Fall 2021C# Programming 3

bool HighScore(int val)

{

return val > 95;

}

Same type
as array
element

HighScore

 Sometimes need quick function without all
method syntax

 Lambda expression
int[] certainScores =

Array.FindAll(scores, x => x > 95);

 Question: Function is implicitly typed
means?
◦ Explicit parameter type possible: (int x) => …

Fall 2021C# Programming 4

lambda operator (read as “goes to”)
lambda
expression

parameter

(“anonymous function”)

 If need to do multiple things in anonymous
function, write as lambda statement
int[] certainScores =

Array.FindAll(

scores,

x => x + 10 > 95 // with bonus

);

◦ If need many statements, write as method

x => {

var y = x + 10; // with bonus

return y > 95;

}

Fall 2021C# Programming 5

return keyword for final value

statement in braces

 Delegate: Reference type to store function

 Declare data type
delegate bool ScorePred(int score);

 Use as parameter type
void SelectGrades(

int[] grades, ScorePred pred) {…}

 Pass function for parameter
SelectGrades(scores, x => x > 95);

 Call function via delegate
if (pred(grades[i]))

Fall 2021C# Programming 6

data type name

 Lambda expressions/statements may use
variables from surrounding scope
int highScore = 95;

Predicate pred = x => x > highScore;

highScore = 97;

int[] certainScores =

Array.FindAll(scores, pred);

 Question: Picks out scores above 95 or 97?

 Function stores environment  closure

Fall 2021C# Programming 7

var from outer scope

 For short function, may use lambda expression

 Reference to function stored in delegate type

 Convenient to use with Array class methods

Fall 2021C# Programming 8