Passing delegates as parameters C# with Example



Passing delegates as parameters C# with Example

Delegates can be used as typed function pointers: 
class FuncAsParameters 
{ 
public void Run() 
{ 
DoSomething(ErrorHandler1); 
DoSomething(ErrorHandler2); 
} 
public bool ErrorHandler1(string message) 
{ 
 

Console.WriteLine(message); 
var shouldWeContinue = ... 
return shouldWeContinue; 
} 
public bool ErrorHandler2(string message) 
{ 
// ...Write message   to   file... 
var shouldWeContinue = ... 
return shouldWeContinue; 
} 
public void DoSomething(Func errorHandler) 
{ 
// In here, we don't care what handler we got passed! 
... 
if (...error...) 
{ 
if (!errorHandler("Some error occurred!")) 
{ 
// The handler decided we can't continue 
return; 
} 
} 
} 
} 

0 Comment's

Comment Form

Submit Comment