Getting started with C# LanguageVerbatim StringsOperatorsExtension MethodsCollection InitializersString InterpolationC# 6.0 FeaturesConstructors and FinalizersKeywordsGenericsReflectionInheritanceNull-Coalescing OperatorUsing StatementString Escape SequencesException HandlingNull-conditional OperatorsBuilt-in TypesLambda expressionsAsync-AwaitPropertiesThreadingUsing DirectiveMethodsYield KeywordEventsLINQ QueriesCommon String OperationsExpression TreesOverload ResolutionString.Formatnameof OperatorUnsafe Code in .NETInitializing PropertiesBindingList<T>ILGeneratorObject initializersXML Documentation CommentsPreprocessor directivesDynamic typeAnonymous typesStructsTuplesEnumAccess ModifiersTask Parallel LibraryAttributesGuidSingleton ImplementationDelegatesNullable typesGarbage Collector in .NetNetworkingArraysEquality OperatorLock StatementAction FiltersXmlDocument and the System.Xml namespaceDateTime MethodsBackgroundWorkerPolymorphismStatic ClassesIndexerIDisposable interfaceAliases of built-in typesImmutabilityXDocument and the System.Xml.Linq namespaceC# 7.0 FeaturesPerforming HTTP requestsGenerating Random Numbers in C#LoopingNamed ArgumentsDiagnosticsInterfacesIEnumerableNaming ConventionsAn overview of c# collectionsChecked and UncheckedRecursionFunctional ProgrammingLiteralsCastingNullReferenceExceptionFunc delegatesLINQ to XMLHash FunctionsHandling FormatException when converting string to other typesCryptography (System.Security.Cryptography)INotifyPropertyChanged interfaceValue type vs Reference typeC# 4.0 FeaturesIQueryable interfaceTask Parallel Library (TPL) Dataflow ConstructsStreamRuntime CompileConditional StatementsInteroperabilityOverflowEquals and GetHashCodeType ConversionParallel LINQ (PLINQ)String ManipulationString ConcatenatePartial class and methodsStopwatchesRegex ParsingC# ScriptC# 3.0 FeaturesAsync/await, Backgroundworker, Task and Thread ExamplesTimersFunction with multiple return valuesBinary SerializationMaking a variable thread safeIComparableCode ContractsIteratorsAssemblyInfo.cs ExamplesFile and Stream I/OCode Contracts and AssertionsCachingC# 5.0 FeaturesImplementing Flyweight Design PatternStringBuilderImplementing Decorator Design PatternAccessing DatabasesT4 Code GenerationMicrosoft.Exchange.WebServices.NET Compiler Platform (Roslyn)Data AnnotationUsing SQLite in C#System.Management.AutomationFileSystemWatcherSystem.DirectoryServices.Protocols.LdapConnectionNamed and Optional ArgumentsComments and regionsC# Authentication handlerPointers & Unsafe CodePointersHow to use C# Structs to create a Union type (Similar to C Unions)BigIntegerDependency InjectionReactive Extensions (Rx)Creational Design PatternsCreating a Console Application using a Plain-Text Editor and the C# Compiler (csc.exe)Reading and writing .zip filesGeneric Lambda Query BuilderImport Google ContactsLambda ExpressionsCLSCompliantAttributeObservableCollection<T>Synchronization Context in Async-AwaitICloneableRead & Understand StacktracesLinq to ObjectsASP.NET IdentityAccess network shared folder with username and passwordAsynchronous SocketStructural Design PatternsO(n) Algorithm for circular rotation of an arrayCreating Own MessageBox in Windows Form ApplicationIncluding Font ResourcesObject Oriented Programming In C#Using json.netGetting Started: Json with C#Windows Communication Foundation

Handling FormatException when converting string to other types

Other topics

Converting string to integer

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:

try
{
    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
}
else 
{
 // 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

Contributors

Topic Id: 2886

Example Ids: 9779

This site is not affiliated with any of the contributors.