Skip to content

Instantly share code, notes, and snippets.

@pedrovasconcellos
Last active November 8, 2018 20:58
Show Gist options
  • Save pedrovasconcellos/8d7298de2e6295422c942ac0ca30eb37 to your computer and use it in GitHub Desktop.
Save pedrovasconcellos/8d7298de2e6295422c942ac0ca30eb37 to your computer and use it in GitHub Desktop.
Delegate examples
void Main()
{
Process();
}
delegate double MathAction(double num);
private static void Process()
{
//--DELEGATE - COMMON--INITIAL
MathAction square = delegate(double input)
{
return input * input;
};
Console.WriteLine("square: {0}", square(5));
//--DELEGATE - COMMON--FINAL
//--DELEGATE - PREDICATE--INITIAL
Predicate<string> p1 = obj => obj.Length > 2;
Console.WriteLine(p1("Vasconcellos"));
Predicate<string> p2 = delegate(string obj) { return obj.Length > 2; };
Console.WriteLine(p2("Vasconcellos"));
Predicate<int> pBiggerThan1991 = x => x > 1991;
int[] numbers = { 1990, 1991, 1992, 1993, 1994 };
int number = Array.Find(numbers, pBiggerThan1991);
Console.WriteLine(number);
//--DELEGATE - PREDICATE--FINAL
//--DELEGATE - ACTION--INITIAL
Action<string>[] actions = new Action<string>[]
{
Console.WriteLine,
delegate(string message){ Console.WriteLine($"Function Print: {message}"); }
};
var automobiles = new[] { "bus", "car", "airplane" };
Array.ForEach(actions, x => Array.ForEach(automobiles, x));
//--DELEGATE - ACTION--FINAL
//--DELEGATE - FUNC--INITIAL
Func<List<long>, int, bool> funcBiggerThan = (values, value) =>
{
foreach(var x in values)
{
if(x > value){ values.Remove(x); return true; }
else{ values.Remove(x); return false; }
}
return false;
};
List<long> listInt64 = new List<long> { 0, 1, 2, 3, 4, 5, 6, 7};
var select = from value in new List<long>() { 0, 1, 2, 3, 4, 5, 6, 7}
where funcBiggerThan(listInt64, 2)
select value;
Console.WriteLine(select);
//--DELEGATE - FUNC--FINAL
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment