C# extensions for daily usage

less than 1 minute read | October 19, 2017

Hi everyone! Today I want to share my extensions which I am using in my daily routine.

I want to say, that I used them in every standalone project I worked for (and sometimes job projects) Go and grab them

I won’t update this article in the future. So, check link above for getting newest ones.

Collection extensions

public static List<T> NullToEmpty<T>(this List<T> source)
{
    return source ?? new List<T>();
}
public static T[] ExpandArray<T>(this T[] array, T item)
{
    if (array == null || array.Length == 0)
    {
        array = new[] { item };
        return array;
    }

    var expandedArray = new T[array.Length + 1];
    Array.Copy(array, expandedArray, array.Length);
    expandedArray[array.Length] = item;

    return expandedArray;
}

String’s extensions

public static bool IsNullOrEmpty(this string value)
{
    return string.IsNullOrEmpty(value);
}
public static bool NotNullOrEmpty(this string value)
{
    return !string.IsNullOrEmpty(value);
}

Json helpers (JSON.NET is required)

public static string ToJson<T>(this T obj)
{
    return JsonConvert.SerializeObject(obj, Formatting.Indented);
}

Entity Framework

public static IQueryable<TEntity> Includes<TEntity>(this IQueryable<TEntity> source, 
    params Expression<Func<TEntity, object>>[] includes)
    where TEntity : class
{
    foreach (var include in includes)
    {
        source = source.Include(include);
    }
    
    return source;
}

Conclusion

That’s all. I’ll be happy, If this link helps you.

Leave a Comment