Truncate Decimal Numbers without Rounding in C#

How to sanitize decimal numbers to the Nth decimal place without rounding.

For example, if you are dealing with crypto numbers like BTC (Bitcoin) or ETH (Etherium).

https://gist.github.com/Protiguous/14d51ba097783f249f1f3b441ed82674#file-sanitize-cs

Premature optimization is the root of all evil.. NOT!

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.

Famous computer scientist Donald Knuth

His quote is often clipped down to just “premature optimization is the root of all evil”, but that is NOT TRUE.

Yes, don’t micro-benchmark everything when you begin a project, but please do think ahead. And once you’ve got the program working as intended, then make it faster by profiling and looking for the bottlenecks.

Choose the proper data structures. Array? List? Hashset? Queue? Dictionary? Caching?
Take a few moments and think it over.

How often will this line of code be ran? Do I need to inline it, or pull it out into a separate method?

Some useful C# Swap methods

public static class SwapExt
{
	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static void Swap<T>(ref T? left, ref T? right) => (left, right) = (right, left);

	[Pure]
	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static (T? right, T? left) Swap<T>(this T? left, T? right) => (right, left);

	[Pure]
	[MethodImpl(MethodImplOptions.AggressiveInlining)]
	public static (T? right, T? left) Swap<T>((T? left, T? right) tuple) => (tuple.right, tuple.left);
}

Pay close attention to which method you think is being used. (The refs versus the tuples.)

C# null coalescing operator, ??

C# has a nice ?? operator that can be chained.
In a statement, it will return the first non-null value or null if none are found to not be null.

For example, if you had the code:

string? value1 = null;
string? value2 = nameof(value2);
string? result = value1 != null ? value1 : value2;

The last line could be simplified down to:

string result = value1 ?? value2;

As far as I know, there is no limit on how many ?? can be chained!

How to [Smartly] add SQL Braces in C#

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.

Boolean Parsing Constants in C#


		/// <summary>
		/// N, 0, no, false, fail, failed, failure, bad
		/// </summary>
		[NotNull]
		[ItemNotNull]
		public static readonly String[] FalseStrings = {
			"N", "0", "no", "false", Boolean.FalseString, "fail", "failed", "failure", "bad"
		};

		/// <summary>
		/// Y, 1
		/// </summary>
		[NotNull]
		public static readonly Char[] TrueChars = {
			'Y', '1'
		};

		/// <summary>
		/// Y, 1, yes, true, Success, good, Go, Positive, Continue
		/// </summary>
		[NotNull]
		[ItemNotNull]
		public static readonly String[] TrueStrings = {
			"Y", "1", "yes", "true", Boolean.TrueString, nameof( Status.Success ), "good", nameof( Status.Go ), nameof( Status.Positive ), nameof( Status.Continue ), nameof(Status.Okay)
		};

How to convert any object to a Boolean value in C#

        /// <summary>
        ///     <para>Returns true if <paramref name="value" /> is a true, 'Y', "yes", "true", "1", or '1'.</para>
        ///     <para>Returns false if <paramref name="value" /> is a false, 'N', "no", "false", or '0'.</para>
        ///     <para>A null will return false.</para>
        /// </summary>
        /// <param name="value"></param>
        [Pure]
        public static Boolean ToBoolean<T>( [CanBeNull] this T value ) {
            switch ( value ) {
                case null: return false;

                case Boolean b: return b;

                case Char c: return c.In( ParsingConstants.TrueChars );

                case Int32 i: return i >= 1;

                case String s when String.IsNullOrWhiteSpace( s ): return false;

                case String s: {
                    var clean = s.Trimmed();

                    if ( clean is null ) {
                        return false;
                    }

                    if ( clean.In( ParsingConstants.TrueStrings ) ) {
                        return true;
                    }

                    if ( Boolean.TryParse( clean, out var result ) ) {
                        return result;
                    }

                    break;
                }
            }

            var t = value.ToString();

            if ( !String.IsNullOrWhiteSpace( t ) ) {
                t = t.Trim();

                if ( t.In( ParsingConstants.TrueStrings ) ) {
                    return true;
                }

                if ( t.In( ParsingConstants.FalseStrings ) ) {
                    return false;
                }

                if ( Boolean.TryParse( t, out var rest ) ) {
                    return rest;
                }
            }

            return false;
        }

        [DebuggerStepThrough]
        [Pure]
        public static Boolean? ToBooleanOrNull<T>( [CanBeNull] this T value ) {
            switch ( value ) {
                case null: return default( Boolean? );

                case Boolean b: return b;

                case Char c: return c.In( ParsingConstants.TrueChars );

                case Int32 i: return i >= 1;

                case String s when String.IsNullOrWhiteSpace( s ): return default( Boolean? );

                case String s: {
                    var trimmed = s.Trimmed();

                    if ( trimmed is null ) {
                        return default( Boolean? );
                    }

                    if ( trimmed.In( ParsingConstants.TrueStrings ) ) {
                        return true;
                    }

                    if ( trimmed.In( ParsingConstants.FalseStrings ) ) {
                        return default( Boolean? );
                    }

                    if ( Boolean.TryParse( trimmed, out var result ) ) {
                        return result;
                    }

                    break;
                }
            }

            var t = value.ToString();

            if ( String.IsNullOrWhiteSpace( t ) ) {
                return default( Boolean? );
            }

            t = t.Trim();

            if ( t.In( ParsingConstants.TrueStrings ) ) {
                return true;
            }

            if ( t.In( ParsingConstants.FalseStrings ) ) {
                return default( Boolean? );
            }

            return Boolean.TryParse( t, out var rest ) ? rest : default( Boolean? );
        }

                public static Boolean ToBooleanOrThrow<T>( [CanBeNull] this T value ) =>
            value.ToBooleanOrNull() ?? throw new FormatException( $"Unable to convert {nameof( value ).SmartQuote()} [{value}] to a boolean value." );

		/// <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;

		/// <summary>
		/// N, 0, no, false, fail, failed, failure, bad
		/// </summary>
		[NotNull]
		[ItemNotNull]
		public static readonly String[] FalseStrings = {
			"N", "0", "false", Boolean.FalseString, "fail", "failed", "stop", nameof( Status.Bad ), nameof( Status.Failure ), nameof( Status.No ),
			nameof( Status.Negative )
		};

		/// <summary>
		/// Y, 1
		/// </summary>
		[NotNull]
		public static readonly Char[] TrueChars = {
			'Y', '1'
		};

		/// <summary>
		/// Y, 1, yes, true, Success, good, Go, Positive, Continue
		/// </summary>
		[NotNull]
		[ItemNotNull]
		public static readonly String[] TrueStrings = {
			"Y", "1", "yes", "true", Boolean.TrueString, nameof( Status.Success ), "good", nameof( Status.Go ), nameof( Status.Positive ), nameof( Status.Continue ), nameof(Status.Okay)
		};