some call them functions, or procedures.
// Simple method
public static void PrintHello()
{
Console.WriteLine("Hello Nick!");
}
simple and do one thing
// Simple method
public static void PrintHello(string name)
{
Console.WriteLine($"Hello {name}!");
}
Take arguments and have parameters
// Simple method
public static int SquareANumber(int x)
{
return x * x;
}
Return a value
// Simple method
public static int SquareNumber(int x) => x * x;
Bonus: One-Liner!
// Simple method
public static int GetCardsTotal(List<Card> cards)
{
var total = 0;
for(var i = 0; i < cards.Count; i++)
{
total += cards[i].GetCardValue();
}
return total;
}
Practical Example
For loops can very useful, but very tedious to use, hard to keep track off and can easily let use create "spaghetti code".
Instead of a for loop, we use take the patterns that for loops create, and create simpler methods that emphasize simplicity, readability and reuse.
In C#, these special methods
for (let i = 0; i < people.Count; i++){
Console.WriteLine(people[i]);
ShowGreatingToPerson(people[i]);
AddPersonToDOM(people[i]);
}
foreach(var person in people)
{
Console.WriteLine(person);
ShowGreatingToPerson(person);
AddPersonToDOM(person);
}
image credit of: https://www.wenovio.com/2017/04/11/javascript-manipuler-vos-donnees-mapfilterreduce/
public class Person {
public string Name {get;set;}
public DateTime Birthday {get;set;}
public string ShirtColor {get;set;}
public int NumberOfApples {get;set;}
}
var birthdays = new List<string>();
for(var i = 0; i < people.Count; i++){
var birthdayAsString =
people[i].Birthday.Month
+ '/' + people[i].Birthday.Day;
birthdays.Add(birthdayAsString);
}
var birthdays = people.Select(person => {
return person.birthday.month +
'/' +
person.birthday.day
});
var orangeShirtedPeople = new List<Person>();
for(var i = 0; i < people.Count; i++){
if (people[i].Shirt == "orange"){
orangeShirtedPeople.Add(people[i]);
}
}
var orangeShirtedPeople =
people.Where(person => person.Shirt == "orange");
var totalApples = 0;
for(var i = 0; i < people.length; i++){
totalApples += people[i].apples
}
int totalApples =
people.Aggregate(
0,
(total, person) =>
total + person.NumberOfApples);
image credit of: https://www.wenovio.com/2017/04/11/javascript-manipuler-vos-donnees-mapfilterreduce/