Tryparse c что это

от admin

Parse and TryParse in C#

Often, our applications depend on external data sources that provide the string representations of .NET types. We have an option of using the Parse and TryParse methods to convert these string representations back to the base .NET types.

The strings can be of any type ranging from numeric, date and time, boolean, chars, or enums. However, let’s focus on parsing numeric strings using Parse() and TryParse() in this article.

The Parse() Method

We use the Parse() method to convert a string representation of a number to its numerical value. It returns the converted numerical value if the conversion is successful. The Parse() method throws an exception if the conversion fails. The exception can be:

  • an ArgumentNullException , if the input string is null
  • a FormatException , if the input string is of incorrect format
  • an OverFlowException , if the converted number exceeds the minimum or maximum range of the specified numeric type

Let’s look at the Parse() method overloads.

Parse(String)

We are most likely to encounter this overload of the Parse() method. It converts a string representation of a number to its numerical value.

For the Parse() method to work, we need to pass a valid string. A valid input string would be a sequence of digits from 0 to 9. Optionally, we can also have a leading and trailing whitespace along with a leading sign (+/-).

Let’s demonstrate this with an example of the Parse(String) method from the System.Int32 class:

Parse(String, IFormatProvider)

This overload of the Parse() method converts a string representation of a number that is in a culture-specific format to its numerical value.

Let’s consider a culture where we denote positive numbers by a leading # sign. Hence, in this culture, the number 1234 would become #1234. However, #1234 is not a valid number in other cultures and would fail to convert. In such a scenario, we specify the culture using Parse(String, IFormatProvider) :

A valid input string for Parse(String, IFormatProvider) is a sequence of digits from 0 to 9 with optional leading and trailing spaces along with a leading sign.

Parse(String, NumberStyles)

This overload of the Parse() method converts a string to its numerical value based on the specified style of the number.

We use the NumberStyles enum to specify the style elements such as separator symbols or exponential digits etc.

The combination of NumberStyles flags affect what a valid input string is. Along with the sequence of digits from 0 to 9, it may also contain leading and trailing signs, thousand operators, etc.:

Parse(String, NumberStyles, IFormatProvider)

This overload of the Parse() method combines the former two overloads. We use it to convert a number’s string representation in a culture-specific format to its numerical value based on a specified style:

Thus, we conclude all the overloads of the Parse() method. Let’s turn our attention to the TryParse() method.

The TryParse() Method

The TryParse() method helps us avoid exceptions when parsing. Here, as a return value, we get a boolean flag indicating whether the conversion was successful. The last parameter contains the result of the conversion and is preceded by the out keyword.

In case of an unsuccessful conversion, the out parameter contains the default value of the specified type.

Because there is no exception handling involved, the TryParse() method performs better than Parse() .

Let’s see which TryParse() overloads are available to us.

TryParse(String, Int32)

This is the most commonly used overload of the TryParse() method. We use it to convert a number’s string representation to its numerical value.

The System.Int32 parameter contains the resulting numerical value if the conversion is successful or a zero in case of failure.

So, with TryParse() instead of throwing exceptions or coding by exceptions, we can use the returned bool flag to control our code flow.

TryParse(String, NumberStyles, IFormatProvider, Int32)

This overload of TryParse() is similar to Parse(String, NumberStyles, IFormatProvider) . We use it to convert a string representation of a number in a culture-specific format to its numerical value based on the specified style.

Let’s continue using our examples for Parse(String, NumberStyles, IFormatProvider) to understand the difference:

TryParse(ReadOnlySpan<Char>, Int32)

We use this overload of the TryParse() method to convert a number’s span representation to its numerical value.

This works similar to the TryParse(String, Int32) with the difference being ReadOnlySpan<Char> instead of String as the input parameter:

TryParse(ReadOnlySpan<Char>, NumberStyles, IFormatProvider, Int32)

This overload of TryParse() is similar to TryParse(String, NumberStyles, IFormatProvider, Int32) . However, we pass ReadOnlySpan<Char> instead of a String here.

Читать:
Как сделать книгу в visual studio

We use it to convert a span representation of a number in a specified style and culture-specific format to its numerical value.

Parsing Other Numeric Strings

We’ve learned about parsing numeric strings using Parse() and TryParse(). However, the examples focus on System.Int32 .

What about the other numeric types?

All the other numeric types have their respective Parse() and TryParse() methods with overloads similar to System.Int32 .

So instead of an int.Parse() , we would use long.Parse() , double.Parse() , or a decimal.Parse() depending on whether the string representation (or span representation when applicable) is of a System.Int64 , System.Double , or a System.Decimal number respectively.

The same is applicable for TryParse with long.TryParse() , double.TryParse() , decimal.TryParse() etc.

Conclusion

In the article, we learned about how the Parse and TryParse in C# work and their different overloads.

Parse() is useful in the scenarios where we care about the type of exception that can occur during failure to convert a string to its numerical value. Whereas, with TryParse() we get a better alternative in terms of performance and reliability by not having to deal with exception handling.

Hence, in cases where we don’t need the exact details of the exceptions, it’s almost always better to go with TryParse() .

Tryparse c что это

Все примитивные типы имеют два метода, которые позволяют преобразовать строку к данному типу. Это методы Parse() и TryParse() .

Метод Parse() в качестве параметра принимает строку и возвращает объект текущего типа. Например:

Стоит отметить, что парсинг дробных чисел зависит от настроек текущей культуры. В частности, для получения числа double я передаю строку «23,56» с запятой в качестве разделителя. Если бы я передал точку вместо запятой, то приложение выдало ошибку выполнения. На компьютерах с другой локалью, наоборот, использование запятой вместо точки выдало бы ошибку.

Чтобы не зависеть от культурных различий мы можем установить четкий формат с помощью класса NumberFormatInfo и его свойства NumberDecimalSeparator :

В данном случае в качестве разделителя устанавливается точка. Однако тем не менее потенциально при использовании метода Parse мы можем столкнуться с ошибкой, например, при передачи алфавитных символов вместо числовых. И в этом случае более удачным выбором будет применение метода TryParse() . Он пытается преобразовать строку к типу и, если преобразование прошло успешно, то возвращает true . Иначе возвращается false:

Если преобразование пройдет неудачно, то исключения никакого не будет выброшено, просто метод TryParse возвратит false, а переменная number будет содержать значение по умолчанию.

Convert

Класс Convert представляет еще один способ для преобразования значений. Для этого в нем определены следующие статические методы:

Преобразование строки в целое число в C#

В этом посте мы обсудим, как преобразовать строку в эквивалентное целочисленное представление в C#.

1. Использование Int32.Parse() метод

Чтобы преобразовать строковое представление числа в эквивалентное ему 32-разрядное целое число со знаком, используйте метод Int32.Parse() метод.

The Int32.Parse() метод выдает FormatException если строка не числовая. Мы можем справиться с этим с помощью блока try-catch.

2. Использование Int32.TryParse() метод

Лучшей альтернативой является вызов Int32.TryParse() метод. Он не генерирует исключение, если преобразование завершается неудачно. Если преобразование не удалось, этот метод просто возвращает false.

3. Использование Convert.ToInt32() метод

The Convert.ToInt32 можно использовать для преобразования указанного значения в 32-разрядное целое число со знаком.

Этот метод выдает FormatException если строка не числовая. Это можно решить с помощью блока try-catch.

Это все о преобразовании строки в целое число в C#.

Оценить этот пост

Средний рейтинг 5 /5. Подсчет голосов: 27

Голосов пока нет! Будьте первым, кто оценит этот пост.

Сожалеем, что этот пост не оказался для вас полезным!

Расскажите, как мы можем улучшить этот пост?

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования ��

Пытаюсь понять методы Parse() и TryParse() и класс Convert

Прочтал про эти 2 метода и класс на разных сайтах. С Convert все понятно, но с 2 -мя методами возикла сложность и в чем их отличия ?

Метод int.Parse(string s) пробует получить число из его строкового представления, в случае успеха возвращает число, иначе же бросает FormatException .

Метод int.TryParse(string s, out int result) проверяет, можно ли получить число из строки. Если это возможно — возвращает true и полученное число out -параметром, иначе возвращает false результатом и default(int) out -параметром.

Это если по-простому, на самом деле могут выбрасываться и другие исключения, в зависимости от того, что за строку вы передаете.

Похожие статьи