Skip to content

Instantly share code, notes, and snippets.

@alxsimo
Created June 3, 2015 08:20
Show Gist options
  • Save alxsimo/795c99e6635c02fa92b1 to your computer and use it in GitHub Desktop.
Save alxsimo/795c99e6635c02fa92b1 to your computer and use it in GitHub Desktop.
[C#] Extension methods
public static string FormatString(this string format, params object[] args)
{
return string.Format(format, args);
}
// usage
string message = "Welcome {0} (Last login: {1})".FormatString(userName, lastLogin);
public static bool IsNull(this object source)
{
return source == null;
}
// usage
public void ProcessData(DataSet input)
{
if (!input.IsNull())
{
// business logic here
}
}
public static TResult NullSafe<TObj, TResult>(
this TObj obj,
Func<TObj, TResult> func,
TResult ifNullReturn = default(TResult))
{
return obj != null ? func(obj) : ifNullReturn;
}
// usage
foo.NullSafe(f => f.GetBar())
.NullSafe(b => b.Baz)
.NullSafe(b => b.SomeMethod(), ifNullReturn: "whatever you would return in the null case");
public static class Throw<TException> where TException : Exception
{
public static void If(bool condition, string message)
{
if (condition)
{
throw (TException)Activator.CreateInstance(typeof(TException),
message);
}
}
}
public static class Traverse
{
public static IEnumerable<T> Along<T>(T node, Func<T, T> next)
where T : class
{
for (var current = node; current != null; current = next(current))
{
yield return current;
}
}
}
// usage
catch (Exception ex)
{
var sqlException = Traverse.Along(ex, e => e.InnerException)
.OfType<SqlException>()
.FirstOrDefault();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment