C Sharp TutorialC Sharp .NET Compiler Platform (Roslyn)C Sharp 3.0 FeaturesC Sharp 4.0 FeaturesC Sharp 5.0 FeaturesC Sharp 6.0 FeaturesC Sharp 7.0 FeaturesC Sharp Access ModifiersC Sharp Access network shared folder with username and passwordC Sharp Accessing DatabasesC Sharp Action FiltersC Sharp Aliases of built-in typesC Sharp an overview of collectionsC Sharp Anonymous typesC Sharp ArraysC Sharp ASP.NET IdentityC Sharp AssemblyInfo.cs ExamplesC Sharp Async-AwaitC Sharp Async/await, Backgroundworker, Task and Thread ExamplesC Sharp Asynchronous SocketC Sharp AttributesC Sharp Authentication handlerC Sharp BackgroundWorkerC Sharp BigIntegerC Sharp Binary SerializationC Sharp BindingListC Sharp Built-in TypesC Sharp CachingC Sharp CastingC Sharp Checked and UncheckedC Sharp CLSCompliantAttributeC Sharp Code ContractsC Sharp Code Contracts and AssertionsC Sharp Collection InitializersC Sharp Comments and regionsC Sharp Common String OperationsC Sharp Conditional StatementsC Sharp Constructors and FinalizersC Sharp Creating Own MessageBox in Windows Form ApplicationC Sharp Creational Design PatternsC Sharp Cryptography (System.Security.Cryptography)C Sharp Data AnnotationC Sharp DateTime MethodsC Sharp DelegatesC Sharp Dependency InjectionC Sharp DiagnosticsC Sharp Dynamic typeC Sharp EnumC Sharp Equality OperatorC Sharp Equals and GetHashCodeC Sharp EventsC Sharp Exception HandlingC Sharp Expression TreesC Sharp Extension MethodsC Sharp File and Stream I/OC Sharp FileSystemWatcherC Sharp Func delegatesC Sharp Function with multiple return valuesC Sharp Functional ProgrammingC Sharp Garbage Collector in .NETC Sharp Generating Random NumbersC Sharp Generic Lambda Query BuilderC Sharp GenericsC Sharp Getting Started: Json with C SharpC Sharp GuidC Sharp Handling FormatException when converting string to other typesC Sharp Hash FunctionsC Sharp ICloneableC Sharp IComparableC Sharp IDisposable interfaceC Sharp IEnumerableC Sharp ILGeneratorC Sharp ImmutabilityC Sharp Implementing Decorator Design PatternC Sharp Implementing Flyweight Design PatternC Sharp Import Google ContactsC Sharp Including Font ResourcesC Sharp IndexerC Sharp InheritanceC Sharp Initializing PropertiesC Sharp INotifyPropertyChanged interfaceC Sharp InterfacesC Sharp InteroperabilityC Sharp IQueryable interfaceC Sharp IteratorsC Sharp KeywordsC Sharp Lambda expressionsC Sharp Lambda ExpressionsC Sharp LINQ QueriesC Sharp LINQ to Objects

C Sharp Handling FormatException when converting string to other types

From WikiOD

Converting string to integer[edit | edit source]

There are various methods available for explicitly converting a string to an integer, such as:

  1. Convert.ToInt16();
  2. Convert.ToInt32();
  3. Convert.ToInt64();
  4. int.Parse();

But all these methods will throw a FormatException, if the input string contains non-numeric characters. For this, we need to write an additional exception handling(try..catch) to deal them in such cases.

Explanation with Examples:

So, let our input be:

string inputString = "10.2";

Example 1: Convert.ToInt32()

int convertedInt = Convert.ToInt32(inputString); // Failed to Convert 
// Throws an Exception "Input string was not in a correct format."

Note: Same goes for the other mentioned methods namely - Convert.ToInt16(); and Convert.ToInt64();  

Example 2: int.Parse()

int convertedInt = int.Parse(inputString); // Same result "Input string was not in a correct format.

How do we circumvent this?

As told earlier, for handling the exceptions we usually need a try..catch as shown below:

    string inputString = "10.2";
    int convertedInt = int.Parse(inputString);
catch (Exception Ex)
    //Display some message, that the conversion has failed.         

But, using the try..catch everywhere will not be a good practice, and there may be some scenarios where we wanted to give 0 if the input is wrong, (If we follow the above method we need to assign 0 to convertedInt from the catch block). To handle such scenarios we can make use of a special method called .TryParse().

The .TryParse() method having an internal Exception handling, which will give you the output to the out parameter, and returns a Boolean value indicating the conversion status (true if the conversion was successful; false if it failed). Based on the return value we can determine the conversion status. Lets see one Example:

Usage 1: Store the return value in a Boolean variable

 int convertedInt; // Be the required integer
 bool isSuccessConversion = int.TryParse(inputString, out convertedInt);

We can check The variable isSuccessConversion after the Execution to check the conversion status. If it is false then the value of convertedInt will be 0(no need to check the return value if you want 0 for conversion failure).

Usage 2: Check the return value with if

if (int.TryParse(inputString, out convertedInt))
    // convertedInt will have the converted value
    // Proceed with that
 // Display an error message

Usage 3: Without checking the return value you can use the following, if you don't care about the return value (converted or not, 0 will be ok)

int.TryParse(inputString, out convertedInt);
// use the value of convertedInt
// But it will be 0 if not converted