ExtensionMethod.NET Home of 880 C#, Visual Basic, F# and Javascript extension methods

EnsureStartsWith

Ensures that a string starts with a given prefix.

Source

/// <summary>
/// 	Ensures that a string starts with a given prefix.
/// </summary>
/// <param name = "value">The string value to check.</param>
/// <param name = "prefix">The prefix value to check for.</param>
/// <returns>The string value including the prefix</returns>
/// <example>
/// 	<code>
/// 		var extension = "txt";
/// 		var fileName = string.Concat(file.Name, extension.EnsureStartsWith("."));
/// 	</code>
/// </example>
public static string EnsureStartsWith(this string value, string prefix)
{
    return value.StartsWith(prefix) ? value : value.Insert(0, prefix);
}

Example

var extension = "jpg";
var file = $({newfilename}{extension.EnsureStartsWith(".")}

or 

var logLine = "| New log line".EnsureStartsWith(DateTime.Now.ToString);

Author: John Tolar

Submitted on: 25 mrt. 2022

Language: csharp

Type: Sysem.String

Views: 2810