Created
May 19, 2015 13:37
-
-
Save miguelangelgonzalez/05394758b22c219c5d30 to your computer and use it in GitHub Desktop.
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
using System; | |
using System.Linq; | |
namespace Common.Extensions | |
{ | |
public static class ObjectExtensions | |
{ | |
public static TProperty GetOrDefault<TObject, TProperty>(this TObject entity, Func<TObject, TProperty> property) | |
{ | |
return entity.GetOrDefault(property, default(TProperty)); | |
} | |
public static TProperty GetOrDefault<TObject, TProperty>(this TObject entity, Func<TObject, TProperty> property, TProperty @default) | |
{ | |
return entity == null ? @default : property(entity); | |
} | |
public static TProperty? GetOrNull<TObject, TProperty>(this TObject entity, Func<TObject, TProperty> property) | |
where TProperty : struct | |
{ | |
return entity == null ? default(TProperty?) : property(entity); | |
} | |
public static T? NullIfDefault<T>(this T val) | |
where T : struct | |
{ | |
return val.Equals(default(T)) ? default(T?) : val; | |
} | |
public static T CastTo<T>(this object obj) | |
{ | |
return (T) obj; | |
} | |
public static T As<T>(this object obj) where T : class | |
{ | |
return obj as T; | |
} | |
public static bool IsAnyOf<T>(this T obj, params T[] others) | |
{ | |
return others.Contains(obj); | |
} | |
public static string Format<T>(this T obj, string format, params Func<T, object>[] parameters) | |
{ | |
var formatParams = parameters.Select(x => x(obj)); | |
return string.Format(format, formatParams.ToArray()); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment