String - ExtractInt16

A string extension method that extracts the Int16 from the string.

Try it

public static void Main()
{	
	string [] input = {"No. 9235", "abc-1538"};

	foreach(var val in input)
	{
		//C# Extension Method: String - ExtractInt16
    	var output = val.ExtractInt16();
		Console.WriteLine(output);
	}
}

View Source
using System;
using System.Text;

public static partial class Extensions
{
    /// <summary>
    ///     A string extension method that extracts the Int16 from the string.
    /// </summary>
    /// <param name="this">The @this to act on.</param>
    /// <returns>The extracted Int16.</returns>
    public static short ExtractInt16(this string @this)
    {
        var sb = new StringBuilder();
        for (int i = 0; i < @this.Length; i++)
        {
            if (Char.IsDigit(@this[i]))
            {
                if (sb.Length == 0 && i > 0 && @this[i - 1] == '-')
                {
                    sb.Append('-');
                }
                sb.Append(@this[i]);
            }
        }

        return Convert.ToInt16(sb.ToString());
    }
}