Using Extension methods with Static methods C# with Example



Using Extension methods with Static methods C# with Example

and Callbacks 
Consider using Extension Methods as Functions which wrap other code, here's a great example that uses both a 
static method and and extension method to wrap the Try Catch construct. Make your code Bullet Proof... 
using System; 
using System.Diagnostics; 
namespace Samples 
{ 
///  
/// Wraps a try catch statement as a static helper which uses 
/// Extension methods for the exception 
///  
public static class Bullet 
{ 
///  
/// Wrapper for Try Catch Statement 
///  
/// Call back for code 
///  Already  handled  and  logged  exception 
public static void Proof(Action code, Action error) 
{ 
try 
{ 
code(); 
} 
catch (Exception iox) 
{ 
//extension method used here 
iox.Log("BP2200-ERR-Unexpected Error"); 
//callback, exception already handled and logged 
error(iox); 
} 
} 
///  
/// Example of a logging method helper, this is the extension method 
///  
/// The Exception to log 
/// A unique error ID header 
public static void Log(this Exception error, string messageID) 
{ 
Trace.WriteLine(messageID); 
Trace.WriteLine(error.Message); 
Trace.WriteLine(error.StackTrace); 
Trace.WriteLine(""); 
} 
} 
///  
/// Shows how to use both the wrapper and extension methods. 
///  
public class UseBulletProofing 
 

{ 
public UseBulletProofing() 
{ 
var ok = false; 
var result = DoSomething(); 
if (!result.Contains("ERR")) 
{ 
ok = true; 
DoSomethingElse(); 
} 
} 
///  
/// How to use Bullet Proofing in your code. 
///  
/// A string 
public string DoSomething() 
{ 
string result = string.Empty; 
//Note that the Bullet.Proof method forces this construct. 
Bullet.Proof(() => 
{ 
//this is the code callback 
result = "DST5900-INF-No Exceptions in this code"; 
}, error => 
{ 
//error is the already logged and handled exception 
//determine the base result 
result = "DTS6200-ERR-An exception happened look at console log"; 
if (error.Message.Contains("SomeMarker")) 
{ 
 //filter the result for Something within the exception message 
result = "DST6500-ERR-Some marker was found in the exception"; 
} 
}); 
return result; 
} 
///  
/// Next step in workflow 
///  
public void DoSomethingElse() 
{ 
//Only called if no exception was thrown before 
} 
} 
} 
 

0 Comment's

Comment Form