Is there a string.TryFormat method that works similar to string.Format?

In any case, check if the argument to string.format is a valid argument, something like string.TryFormat.

try { string.Format(Format, new string[Selectors.Count]); // } catch (Exception) { return false; } 

I use this method in my user interface and its slow and noticeable when an Exception is called, so I was wondering if there is a better way to use it.

I could always write my own method, but I wanted to know if there was a predefined one.

Invalid line The format will be something like this line .Format ("Format {0} {1} {2}", new line [] {"a", "b"})

+6
source share
1 answer

The only way the System.String.TryFormat method could work is to catch any exceptions that can be IFormattable.ToString from various IFormattable.ToString implementations (although String.TryFormat can replace some of its own exceptions by returning an error flag, doing so, freeing it up exceptions from TryFormat escape will not be very useful).

Worse, the TryFormat method would have no way of knowing if any of the exceptions thrown by IFormattable.ToString be things that should not be caught. Even if the IFormattable.ToString contract required implementations to pass nothing but a FormatException if the format specifier was invalid, it would probably require the String.TryFormat method String.TryFormat return false (rather than throwing) if some of the input objects were invalid. but the attempt to format them did nothing worse, while the exception was leaked if the process of formatting the elements itself caused corruption. Unfortunately, the way to create an exception hierarchy, there is no way that String.TryFormat can even come close to such semantics.

Simply put, there isn't much that the String.TryFormat method can use other than using the try / catch to stifle the exceptions thrown by internal methods. There, the normal meaning is that TryXX methods should work better in the event of a crash than a regular program that just did XX in a try-catch block. If the TryFormat method just works, stifling exceptions anyway, it could also allow this user to handle this.

+7
source

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


All Articles