If you need a SQL object correctly quoted by the [ and ] braces.
/// <summary>
/// Add the left [ and right ] braces if they're not already on the string.
/// <para>An empty or whitepsace string throws <see cref="ArgumentEmptyException"/>.</para>
/// </summary>
/// <param name="self"></param>
/// <returns></returns>
/// <exception cref="ArgumentEmptyException"></exception>
[DebuggerStepThrough]
[NotNull]
[Pure]
public static String SmartBraces( [NotNull] this String? self ) {
self = self.Trimmed();
if ( String.IsNullOrEmpty( self ) ) {
throw new ArgumentEmptyException( nameof( self ) );
}
if ( self.StartsWith( "[", StringComparison.Ordinal ) && self.EndsWith( "]", StringComparison.Ordinal ) ) {
self = self[ 1..^1 ]?.Trim();
}
if ( String.IsNullOrEmpty( self ) ) {
throw new ArgumentEmptyException( nameof( self ) );
}
return $"{'['}{self}{']'}";
}
/// <summary>Trim the ToString() of the object; returning null if null, empty, or whitespace.</summary>
/// <param name="self"></param>
/// <returns></returns>
[DebuggerStepThrough]
[CanBeNull]
[Pure]
public static String? Trimmed<T>( [CanBeNull] this T self ) =>
self switch {
null => default( String? ),
String s => s.Trim().NullIfEmpty(),
var _ => self.ToString()?.Trim().NullIfEmpty()
};
/// <summary>Returns null if <paramref name="self" /> is <see cref="String.IsNullOrEmpty" />.</summary>
/// <param name="self"></param>
/// <returns></returns>
[CanBeNull]
[DebuggerStepThrough]
[Pure]
public static String? NullIfEmpty( [CanBeNull] this String? self ) => String.IsNullOrEmpty( self ) ? null : self;
//Note: All attributes can be removed.