String - LeftSafe

A string extension method that return the left part of the string safely, if length passed as parameter is greater than the length of the string object, then orginal string is returned.

Try it

public static void Main()
{
	string input = "OneTwoThree";

	// C# Extension Method: String - LeftSafe
    string newStr = input.LeftSafe(6);
	Console.WriteLine(newStr);
	
	// C# Extension Method: String - LeftSafe
	newStr = input.LeftSafe(16);
	Console.WriteLine(newStr);
}

View Source
using System;

public static partial class Extensions
{
    /// <summary>
    ///     A string extension method that left safe.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <param name="length">The length.</param>
    /// <returns>A string.</returns>
    public static string LeftSafe(this string @this, int length)
    {
        return @this.Substring(0, Math.Min(length, @this.Length));
    }
}