Created
November 22, 2012 02:34
-
-
Save hnh12358/4129130 to your computer and use it in GitHub Desktop.
NullDefender
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//After working with a Functional Language I can't help to think that the world will be more | |
//safe without all the need to be checking for null values. | |
//This is an small helper I wrote to stop writing 'null' every once in a while. | |
namespace Horacio.Helpers | |
{ | |
using System.Net.NetworkInformation; | |
public static class ObjectHelper | |
{ | |
public static void NullDefender<TSubject>(this object instance, | |
TSubject subject, | |
Action<TSubject> action) | |
where TSubject : class | |
{ | |
if (subject != null) action.Invoke(subject); | |
} | |
public static TReturnType NullDefender<TSubject, TReturnType>(this object instance, | |
TSubject subject, | |
TReturnType onNullResult, | |
Func<TSubject, TReturnType> action) | |
where TSubject : class | |
{ | |
return subject != null ? action.Invoke(subject) : onNullResult; | |
} | |
} | |
public class InstanceInternetVerifier | |
{ | |
public bool IsInternetAvailable() | |
{ | |
var ping = new Ping(); | |
return this.NullDefender(ping.Send("horatio.info"), | |
false, | |
x => x.Status == IPStatus.Success); //The new "instance" method. | |
} | |
} | |
public static class StaticInternetVerifier | |
{ | |
public static bool IsInternetAvailable() | |
{ | |
var ping = new Ping(); | |
return this.NullDefender(ping.Send("horatio.info"), | |
false, | |
x => x.Status == IPStatus.Success); //Doesn't work on static methods. | |
//We can use just 0, or have something like: | |
//Core.Lang were Lang will be an static property | |
//of a Core classs. | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment