Appccelerate.Formatters.FormatHelper.SecureFormat C# (CSharp) Method

SecureFormat() public static method

Replacement for the String.Format method, that throws an exception when the count of arguments does not match the count of placeholders.

If format and/or arguments are null then still a string is returned.

Tries to format with String.Format. In case of an Exception the original format string and all parameters added in a list will be returned.
public static SecureFormat ( IFormatProvider formatProvider, string format ) : string
formatProvider IFormatProvider /// The format Provider. ///
format string /// The format string. ///
return string
        public static string SecureFormat(IFormatProvider formatProvider, string format, params object[] args)
        {
            if (format == null) 
            {
                // no format string
                return string.Empty;
            }

            // no arguments, just use format
            if (args == null) 
            {
                return format;
            }
            
            try
            {
                return string.Format(formatProvider, format, args);
            }
            catch (FormatException)
            {
                string result = "!!! FORMAT ERROR !!!! " + format + ": ";

                return args.Aggregate(result, (current, arg) => current + (arg + ", "));
            }
        }

Usage Example

Example #1
0
        public void SecureFormat_ReturnsErrorString_WhenTooFewParameters()
        {
            const string Format   = "{0} {1} {2}";
            const string Expected = "!!! FORMAT ERROR !!!! " + Format + ": ";
            const int    I        = 1;

            string result = FormatHelper.SecureFormat(CultureInfo.InvariantCulture, Format, I);

            result.Should().Be(Expected + I + ", ", "too few parameters.");
        }
All Usage Examples Of Appccelerate.Formatters.FormatHelper::SecureFormat