Перейти к содержимому

Parse c что это

  • автор:

How to Convert a String to an Int in C# – Tutorial with Example Code

Ondrej Polesny

Ondrej Polesny

How to Convert a String to an Int in C# – Tutorial with Example Code

Converting a string to an integer is common practice when you’re dealing with user input, JSON data, API responses, or regular expressions. But what’s the right way to do it for each scenario?

In this article, I’ll explain three ways to convert a string into a number in C# and I’ll show you how to choose the right method for your scenario.

Determine the source of your data

First of all, let’s see where your data is coming from. It’s easy to convert the string «123» into an integer, but in the real world, it’s never that simple.

The «number string» can come from a database, text file, an API, or a user of your app. So how confident are you it’s really a number?

Data source Confidence What can happen
User input �� «1.23»
«hello»
JSON data �� «123.1»
«»
API response �� «11,7»
«»
Regular expression match �� invalid expression allowing not only numbers

How big can your number get?

You also need to know how big your target number can be. In the scope of this article, we’re talking about Int. That is usually considered Int32 ( int ), but you can also use Int16 ( short ) and Int64 ( long ) depending on how large the numbers are that you expect.

Type Largest number
Int16 ( short ) 32767 ( Int16.MaxValue )
Int32 ( int ) 2,147,483,647 ( Int32.MaxValue )
Int64 ( long ) 9,223,372,036,854,775,807 ( Int64.MaxValue )

int.Parse(String) – input confidence: high ��

Use int.Parse when you are sure the input is really a number. It can also parse numbers in culture-specific or other widely-known formats, but you need to know the exact format:

Signature Output
int.Parse(«123») 123
int.Parse(«») throws FormatException
int.Parse(null) throws ArgumentNullException
int.Parse(«123,000») throws FormatException
int.Parse(«123,000»,
System.Globalization.NumberStyles.AllowThousands,
new System.Globalization.CultureInfo(«en-US»))
123000

Convert.ToInt32(String) – input confidence: medium ��

Convert is very similar to int.Parse with one exception: null is converted to 0 and does not throw an exception. It can also handle other input data types (not just strings):

Signature Output
Convert.ToInt32(«123») 123
Convert.ToInt32(«») throws FormatException
Convert.ToInt32(null) 0
Convert.ToInt32(«123,000») throws FormatException
Convert.ToInt32(«1.23») throws FormatException
Convert.ToInt32(1.23) 1

Note: You can use Convert.ToInt32 to remove number precision behind a decimal point. However, to ensure good code readability, you should use Math.Floor to achieve this task.

Int*.TryParse(String, Int32) — input confidence: low ��

Use TryParse whenever you don’t trust your data source. For example, when you’re getting user input or parsing and validating data from submitted forms:

Signature Output
int number;
bool convertible = Int32.TryParse(«123», out number)
number = 123
convertible = True
int number;
bool convertible = Int32.TryParse(«hello», out number)
number = 0
convertible = False
int number;
bool convertible = Int32.TryParse(«», out number)
number = 0
convertible = False

Note: You can also move the number definition to the TryParse method call by typing out int number .

The most typical example is with Console.ReadLine :

Conclusion

In this article, I showed you three ways to convert a number to a string in C# and explained how to decide which method to use based on the source of your data and the confidence you have in it.

Parse and TryParse in C#

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.

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() .

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

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

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

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

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

Parse vs TryParse in .Net

TryParse is a more advanced and powerful version of the Parse() method.

Mendel Bakaleynik

Parse()

The Parse method takes a string as an argument and attempts to translate it back to the specified type. Here’s what it looks like in action.

The problem with the Parse method is that if the argument that is passed to it is invalid, such as bool.Parse(2), bool.Parse("asfsad"), Int32.Parse(null) it will throw an ArgumentNullException error. We want to have our program be able to gracefully handle bad input so we need a more robust method that doesn’t throw errors in the face of bad data.

Enter the TryParse method.

TryParse()

TryParse works a little differently. It takes an input, just like before, and attempts to translate it, just like before. But this method is special since it returns two values, instead of the usual one. The method itself returns a bool value if it was able to successfully translate the argument into the correct format.

That means, we can check the method’s return value to see if the translation/parsing went alright. Here’s what that looks like: (ignore the second parameter for now. We’ll discuss that in a moment.)

Great! Now we learned that the TryParse method itself return a boolean value. But where do I get my actual, translated, value?

You get it from the out variable.

The TryParse method requires that you have an out parameter, which holds the translated value. You can define the variable above the method, or inside the method. You can also ignore the out variable value if all you care about is using the TryParse method to validate a boolean value, but you still have to setup the out variable correctly.

Let’s see some examples.

If we wanted to use the TryParse method to check a configuration setting in our code, return the proper true/false statement, and handle bad input, it would look like this.

Be Aware of False Positives

You should be aware, if the TryParse conversion fails, the out parameter will be false . You should check and guard against this.

That’s all there is to it!

  • Parse() returns the translated value or an error.
  • TryParse will never return an error.
  • TryParse returns 2 things. 1) A boolean value saying if the translation went well or not, and 2) an out variable of the translated value.
  • If TryParse fails to convert, it will set the out param to false .

Advanced

A clever way to use the TryParse method is to use a ternary operator to craft a conditional ref expression.

Let’s say you wanted to evaluate a configuration setting, return the proper true/false statement, prevent errors due to bad input, and default to True in case of bad input, it would look like this.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Школа онлайн с государственным аттестатом