Common methods encountered at work:
Parse and TryParse
The TryParse method is similar to the Parse method, except that the TryParse method does not throw an exception if the conversion fails
1 /// <summary>2 ///The TryParse method is similar to the Parse method, except that the TryParse method does not throw an exception if the conversion fails3 /// </summary>4 Public Static voidtryparseexample ()5 {6String[] values = {NULL,"160519","9432.0","16,667","-322","+4302","(a);","01FA","ab123" };7 foreach(varValueinchvalues)8 {9 intNumber ;Ten One BOOLresult = Int32.TryParse (value, outNumber ); A if(Result) - { -Console.WriteLine ("converted ' {0} ' to {1}.", value, number); the } - Else - { - //if (value = = null) value = ""; +Console.WriteLine ("attempted conversion of ' {0} ' failed.", -Value = =NULL?"<null>": value); + } A } at } - - /// <summary> - /// - /// </summary> - Public Static voidparseexample () in { -String[] values = {NULL,"160519","9432.0","16,667","-322","+4302","(a);","01FA","ab123" }; to foreach(varValueinchvalues) + { - Try the { * intresult =Int32.Parse (value); $Console.WriteLine ("converted ' {0} ' to {1}.", value, result);Panax Notoginseng } - Catch(Exception ex) the { +Console.WriteLine ("Unable to convert ' {0} '.", value); AConsole.WriteLine (string. Format ("{0}-{1}", ex. Message, ex. GetType ())); the } + } -}
C # Parse and TryParse method