Skip to content

Common extension methods

Date extension

Often, we need helper methods like format date time.

csharp
public static class DateHelper
{
    public static string FormatDateTime(DateTime dateTime)
    {
        return dateTime.ToString("yyyy-MM-dd");
    }
}

This requires knowing that the helper exists and calling it looks like DateHelper.FormatDateTime(scheduledStart)

Another approach is using extensions. In Utilities folder, add DateExtension.cs

csharp
public static class DateExtension
{
    public static string FormatDateTime(this DateTime dateTime)
    {
        return dateTime.ToString("yyyy-MM-dd");
    }
}

After typing DateTime.UtcNow., IntelliSense will show FormatDateTime() as a possible method DateTime.UtcNow.FormatDateTime();alt text

String extension

csharp
public static class StringExtension
{
    public static string Truncate(this string value, int maxLength)
    {
        if (string.IsNullOrEmpty(value))
        {
            return value;
        }
        return value.Length <= maxLength ? value : value.Substring(0, maxLength);
    }

    public static bool ContainsIgnoreCase(this string value, string target)
    {
        if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(target))
        {
            return false;
        }
        return value.Trim().Contains(target.Trim(), StringComparison.OrdinalIgnoreCase);
    }

    public static bool EqualsIgnoreCase(this string value, string target)
    {
        if (string.IsNullOrEmpty(value) || string.IsNullOrEmpty(target))
        {
            return false;
        }
        return value.Trim().Equals(target.Trim(), StringComparison.OrdinalIgnoreCase);
    }
}

List extension

csharp
public static class ListExtension
{
    public static bool ContainsIgnoreCase(this List<string> value, string target)
    {
        target = target.Trim();
        return value.Contains(target, StringComparer.OrdinalIgnoreCase);
    }
}

Released under the MIT License.