Can I check if the format specifier is valid for this data type?

If I (in .NET / C #), for example, have a type variable long, I can convert it to a formatted string, for example:

long value = 12345;
string formattedValue = value.ToString("D10"); // returns "0000012345"

If I specify a format that is not valid for this type, I get an exception:

long value = 12345;
string formattedValue = value.ToString("Q10"); // throws a System.FormatException

Question: Is there a way to check if the format specifier is valid (other than trying to format and catch the exception) before applying this format, is it something like long.IsFormatValid("Q10")?

Thanks for the help!

+3
source share
2 answers

I have not tried this, but I would have thought that you could create an extension method, for example:

namespace ExtensionMethods
{
    public static class MyExtensions
    {

        public static bool IsFormatValid<T>(this T target, string Format)
            where T : IFormattable
        {
            try
            {
                target.ToString(Format, null);
            }
            catch
            {
                return false;
            }  
            return true;
        }
    }
}

which you could apply in this way:

long value = 12345;
if (value.IsFormatValid("Q0")) 
{
    ...
+2

, , , , , .

, , , . , ( f, e ..).

, TryParse/Parse.

+2

Source: https://habr.com/ru/post/1779582/


All Articles