Tuesday, June 5, 2018

Action, Delegate, Lambda expression and Callbacks in C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class ActionDemo : MonoBehaviour {
void Start(){
Action<string> SampleAction; //action dont need an explicit delegate to be declared (Action is special kind of delegate which takes parameters but returns nothing)
SampleAction = PrintMsg;
SampleAction += delegate(string s) {Debug.Log("from anonymous method : "+s);} ; //using anonymous method
SampleAction += s => Debug.Log("using lambda expression : "+s); //using lambda expression
SampleAction ("Hello shrinath");
}
void PrintMsg(string msg1){
Debug.Log ("msg : " + msg1);
}
}
view raw ActionDemo.cs hosted with ❤ by GitHub
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class CallbackUsingActionAndLambdaDemo : MonoBehaviour {
void Start(){
DoWork ((String result) => Debug.Log (result)); //passing the executable code to DoWork() as a callback (after doing work in DoWork(), the code which has been sent will be executed)
}
public void DoWork(Action<string> callback){
bool isWorkDone;
//do work here
isWorkDone = true;
if (isWorkDone)
callback ("yes work is done successfully");
else
callback ("sorry work is not done");
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CallbackUsingDelegateDemo : MonoBehaviour {
public delegate void WorkCompletedCallBack(string result);
public void DoWork(WorkCompletedCallBack callback){
bool isWorkDone;
//do work here
isWorkDone = true;
if (isWorkDone)
callback ("yes work done successfully...");
else
callback ("sorry work not done...");
}
void Start(){
WorkCompletedCallBack workResultCallback = ShowWorkResult;
DoWork (workResultCallback);
}
//this is the callback which is called when the work is done in DoWork()
public void ShowWorkResult(string result){
Debug.Log (result);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DelegateDemo : MonoBehaviour {
public delegate void Del(string msg);
void Start(){
Del SampleDel;
SampleDel = PrintMsg;
SampleDel += Debug.Log; //using plus sign we can subscribe multiple methods to trigger events.
SampleDel("Hello Shrinath..."); //when this is called, all the methods subscribed to this delegate gets called
}
void PrintMsg(string msg1){
Debug.Log ("msg : " + msg1);
}
}
view raw DelegateDemo.cs hosted with ❤ by GitHub

No comments:

Post a Comment