Skip to content

Instantly share code, notes, and snippets.

@erdembayar
Last active September 24, 2018 03:24
Show Gist options
  • Save erdembayar/46c2848c591f7558efa80ef8a4fa77c5 to your computer and use it in GitHub Desktop.
Save erdembayar/46c2848c591f7558efa80ef8a4fa77c5 to your computer and use it in GitHub Desktop.
Action vs Delegate vs Func vs Predicate
using System;
using System.Collections.Generic;
using System.Diagnostics;
namespace Action_vs_Func_vs_Predicate
{
class Program
{
public delegate void PrintDelegate(int val);
public delegate void MyDelegate();
static void Main(string[] args)
{
//https://stackoverflow.com/questions/20163326/invoking-an-action-determine-if-the-instance-it-belongs-to-is-null
//https://stackoverflow.com/questions/4965508/how-can-i-pass-a-parameter-in-action
//http://www.tutorialsteacher.com/csharp/csharp-action-delegate
//https://answers.unity.com/questions/1095818/dictionary-of-functions.html
Action act = new Action(PrintSomething);
act.Invoke();
act?.Invoke();
int param = 123;
Action action = new Action(delegate()
{
DoSomething(param);
});
action.Invoke();
action?.Invoke();
Action action1 = new Action(() =>
{
DoSomething(param);
});
action1.Invoke();
Action action2 = new Action(PrintSomething);
action2.Invoke();
Action action3 = PrintSomething; //PrintIt doesn't work since it's not instance nor static
action3.Invoke();
ExecuteAction(action3);
//Action with parameter.
Action<int> action4 = new Action<int>(DoSomething);
action4.Invoke(6);
action4 = null;
action4?.Invoke(7);
//Class method.
var d = new Dummy { Name ="Dummy2" };
Action action5 = d.Method;
action5.Invoke();
action5?.Invoke();
ExecuteAction(action5);
d.Method();
object aaa = null;
string bbb = aaa?.ToString();
d = null;
d?.Method();
action5 = null;
//act2.Invoke(); //This will fail
action5?.Invoke();
ExecuteAction(action5);
Action action6 = Console.WriteLine;
action6.Invoke();
ExecuteAction(action6);
Console.WriteLine("Action 6 is chained");
action6 += action;
action6 += action2;
action6.Invoke();
// ExecuteAction(action6); It also works.
Console.WriteLine("Chained action 6 finish");
Action<int> action7 = (i) => DoSomething(i);
action7.Invoke(22);
Action<int> action8 = (i) => Console.WriteLine(i);
action8.Invoke(33);
////////////////////////////////////////////////
PrintDelegate printDelegate = DoSomething;
printDelegate.Invoke(10);
printDelegate(param);
ExecuteDelegate(printDelegate);
printDelegate = null;
printDelegate?.Invoke(10);
if (printDelegate!=null) //nullable condition doesn't work for delegates.
printDelegate(param);
PrintDelegate printDelegate2 = new PrintDelegate(DoAnotherthing);
printDelegate2(22);
Console.WriteLine("Chained PrintDelegate");
printDelegate = DoSomething;
printDelegate2 += printDelegate;
printDelegate2.Invoke(88);
Console.WriteLine("Chain to itself");
printDelegate2 += printDelegate2;
ExecuteDelegate(printDelegate2); //Called 4 times each.
Console.WriteLine("Chained printDelegate finish.");
MyDelegate myDelegate = Console.WriteLine;
myDelegate.Invoke();
myDelegate();
////////////////////////////////////////////////
//Lambda expressions
Func<int, float> myFunc = n => (float)n / 2;
Console.WriteLine(myFunc(7));
Func<int, bool> mydelegate = z => z < 5;
Console.WriteLine(mydelegate(10));
Console.WriteLine(mydelegate(1));
// Dictionary<string, Func> myFuncDictionary = new Dictionary<string, Func<>>();
//
// Dictionary<int, System.Action> functions = new Dictionary<int, System.Action>();
Console.WriteLine("\nTesting action dictionary no Input.");
Dictionary<int, System.Action> actionDictionaryNoInput = new Dictionary<int, System.Action>();
actionDictionaryNoInput.Add(64, new Program().Function0);
actionDictionaryNoInput.Add(57, Function1);
actionDictionaryNoInput[57]();
actionDictionaryNoInput[64]();
if (actionDictionaryNoInput.ContainsKey(3))
{
actionDictionaryNoInput[3]();
}
Console.WriteLine("\nTesting action dictionary with String Input.");
// https://stackoverflow.com/questions/5125717/how-to-store-functions-in-dictionary-with-uint-as-key-c
var actionDictionaryStringInput = new Dictionary<int, Action<string>>
{
{ 5, x => Console.WriteLine("Action for 5: {0}", x) },
{ 13, x => Console.WriteLine("Unlucky for some: {0}", x) },
{ 16, x => ConsoleReverse(x) }
};
actionDictionaryStringInput[5]("Woot");
actionDictionaryStringInput[13]("Not really");
actionDictionaryStringInput[16]("Foobar");
string h = "";
// You can add later easily too
actionDictionaryStringInput.Add(10, x => Console.WriteLine("Ten {0}", x));
actionDictionaryStringInput.TryGetValue(10, out Action<string> function10);
function10(" ten10");
actionDictionaryStringInput[15] = x => Console.WriteLine("Fifteen {0}", x);
actionDictionaryStringInput[15]("stringOut");
// Method group conversions work too
actionDictionaryStringInput.Add(0, MethodTakingString);
actionDictionaryStringInput[0]("woohoo");
// Dictionary<string, Func<long> > functionDictionary = new Dictionary<string, Func<long>>
// {
// {"aaa", v => Function2(v) }
// };
//
Console.ReadKey();
}
static void DoSomething(int i)
{
Console.WriteLine("Do something: "+i);
}
static void DoAnotherthing(int i)
{
Console.WriteLine("Do anotherthing: " + i);
}
static void PrintSomething()
{
Console.WriteLine("Print something");
}
void PrintIt() //Need instance or make it static
{
Console.WriteLine("Print it");
}
static void ExecuteAction(Action action)
{
// action.Invoke();
action?.Invoke();
}
static void ExecuteDelegate(PrintDelegate deleg)
{
// deleg.Invoke(10);
deleg?.Invoke(10);
if(deleg!=null)
deleg(10);
}
private void Function0()
{
Console.WriteLine("Function 0");
}
private static void Function1()
{
Console.WriteLine("Function 1");
}
private static long Function2(long num)
{
Console.WriteLine("Function 2: " + num);
return num;
}
static void MethodTakingString(string x)
{
Console.WriteLine("Action MethodTakingString: "+x);
}
static void ConsoleReverse(String i)
{
Console.WriteLine("Reverse: " + Reverse(i));
}
public static string Reverse(string s)
{
char[] charArray = s.ToCharArray();
Array.Reverse(charArray);
return new string(charArray);
}
}
public class Dummy
{
public string Name { get; set; } = "Dummy1";
public void Method()
{
Console.WriteLine("Name=" + Name);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment