few extensions I use mostly. first set is object extensions, really only for converting.
public static class ObjectExtension
{
public static T As<T>(this object value)
{
return (value != null && value is T) ? (T)value : default(T);
}
public static int AsInt(this string value)
{
if (value.HasValue())
{
int result;
var success = int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out result);
if (success)
{
return result;
}
}
return 0;
}
public static Guid AsGuid(this string value)
{
return value.HasValue() ? new Guid(value) : Guid.Empty;
}
}
string extensions
public static class StringExtension
{
public static bool HasValue(this string value)
{
return string.IsNullOrEmpty(value) == false;
}
public static string Slug(this string value)
{
if (value.HasValue())
{
var builder = new StringBuilder();
var slug = value.Trim().ToLower();
foreach (var c in slug)
{
switch (c)
{
case ' ':
builder.Append("-");
break;
case '&':
builder.Append("and");
break;
default:
if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') && c != '-')
{
builder.Append(c);
}
break;
}
}
return builder.ToString();
}
return string.Empty;
}
public static string Truncate(this string value, int limit)
{
return (value.Length > limit) ? string.Concat(value.Substring(0, Math.Min(value.Length, limit)), "...") : value;
}
}
and last is some enum extensions
public static class EnumExtensions
{
public static bool Has<T>(this Enum source, params T[] values)
{
var value = Convert.ToInt32(source, CultureInfo.InvariantCulture);
foreach (var i in values)
{
var mask = Convert.ToInt32(i, CultureInfo.InvariantCulture);
if ((value & mask) == 0)
{
return false;
}
}
return true;
}
public static bool Has<T>(this Enum source, T values)
{
var value = Convert.ToInt32(source, CultureInfo.InvariantCulture);
var mask = Convert.ToInt32(values, CultureInfo.InvariantCulture);
return (value & mask) != 0;
}
public static T Add<T>(this Enum source, T v)
{
var value = Convert.ToInt32(source, CultureInfo.InvariantCulture);
var mask = Convert.ToInt32(v, CultureInfo.InvariantCulture);
return Enum.ToObject(typeof(T), value | mask).As<T>();
}
public static T Remove<T>(this Enum source, T v)
{
var value = Convert.ToInt32(source, CultureInfo.InvariantCulture);
var mask = Convert.ToInt32(v, CultureInfo.InvariantCulture);
return Enum.ToObject(typeof(T), value & ~mask).As<T>();
}
public static T AsEnum<T>(this string value)
{
try
{
return Enum.Parse(typeof(T), value, true).As<T>();
}
catch
{
return default(T);
}
}
}