Skip to content

Instantly share code, notes, and snippets.

@hnh12358
Created November 22, 2012 02:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnh12358/4129130 to your computer and use it in GitHub Desktop.
Save hnh12358/4129130 to your computer and use it in GitHub Desktop.
NullDefender
//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