C# Formatting & Parsing With ToString, Parse and IFormattable
Any software application, two of the most frequently done tasks are formatting and parsing the data. In simplest words, formatting refers to the process of converting some type to string and conversely parsing refers to converting string into some other data type. There are several techniques that can be used to perform these two operations in C# .NET, in this article; we will discuss all the major string formatting and parsing techniques. We will explain what the several techniques are and how they can be implemented in application, with the help of several code snippets.
You must be aware of these two methods and you might have used these in past. These are the two most commonly and most widely used formatting and parsing methods in C# .NET. ToString method converts a particular type to a string and Parse method simply does the reverse. For example if you have a bool variable and you initialized it to true and then if you call ToString method on it, it will call the default to string method of the bool type and will display what is stored in it. For instance, consider these lines of code
Similarly, consider the following lines of code
Now let us put the above concepts into a working example. Have a look at Example1.
Now let us come towards the parsing portion of the example. We have created another string s2val and have initialized it to ‘false’. We then called Parse method on bool and passed s2val to it. It will convert the string value ‘false’ into bool vale false and return to the bool variable bval. Now again in order to verify that if our conversion was successful we would test that if the value in bval is true, it means are conversion is unsuccessful, otherwise our conversion has been successful. The output of the code in Example1 is as follows.
Now, an interesting thing to note here is that if the string s2val had a value other than true or false, could it be parsed into bool? Because bool can only have two values: true or false. The answer is that if parse a string variable that contains some string which cannot be parsed into a particular data type to which you are parsing, a FormatException will occur. For example if you change the value of s2val to ‘fals’, removing the terminating ‘e’ and then compile the code, it will throw exception because bool cannot have a value ‘fals’, it can only have values true or false. Therefore the following exception will occur. Have a look at the following screenshot, this will appear.
Although, you can handle this exception in your code using some try catch block, but exception handling is expensive. C# has a better way to handle such scenario via TryParse method. This method doesn’t throw exception, rather it returns false if parsing is not successful. In our next example we are going to show you that how TryParse can be used to avoid exceptions if parsing is not successful. Have a look at Example2.
Special care needs to be taken while parsing strings to DateTime, DateTimeOffset and numeric data types because compiler keep local cultural settings in mind while parsing strings. For example if you parse the string 4.563 into double value and your local cultural settings are set to Germany then the result of t parsing 4.563 into double will be 4563 because in Germany a period is used to represent a thousand separator, not as a traditional mathematical decimal point. Therefore while parsing; you can parse CultureInfo.InvariantCulture as second parameter to negate the effect of the local culture. Same is the case when you call the ToString for formatting purposes. Both of these concepts have been explained in the following lines of code.
Although, ToString method is good enough for formatting purposes, however it doesn’t allow developers to have more control over the conversions. In order to have more control over your conversions, C# .NET allows formatting and parsing using format providers. Format providers can be used for parsing DateTime structs and other numeric data types. In order to use format providers, a class has to implement IFormattable interface. This interface looks like.
All the DateTime structs and numeric types implement the above interface which allows the developers to have more control over formatting. With the help of a working example, I would explain how you can use format providers in your code. Have a look at Example3.
In the next line, we again changed the CurrencySymbol of the format provider ‘format’ and this time we initialized it with “$$ ”, now if we pass this format to the ToString method, we will have ‘$$ ’ appended before the result. Compile the code in Example3 and you should see that first the number is displayed in currency format using Rs. and then using ‘$$ ‘ as format. The output if Example3 is as follows
Now important thing to notice here is that if you omit the second parameter i.e Format Provider and provide null instead, it will have a default format provider i.e. CultureInfo.Current culture. For example, if you write this line in your code,
We passed null, in the lines of code above, however we can also leave the second parameter because most of the numeric and DateTime structs have overwritten the ToString method, where we don’t need to specifically pass the second parameter. Therefore, following lines of code will yield the same result as we mentioned earlier though we are not passing any null value in the second parameter.
If you look at the output you would find that we didn’t passed any format for currency symbol as the second argument, yet in the output a single dollar sign ‘$’ is appended before the amount that we passed. The reason is that since, by default the second parameter is CultureInfo.CurrentCulture and in current culture of my system, the currency symbol is “$” therefore it has been automatically appended before the amount. It can be different in your culture, depending upon your system settings and the region in which you are using application.
In .NET framework, you can pass three types of format providers as the second argument: NumberFormatInfo (Which we used in Example3), DateTimeInfo and CultureInfo. In the last part of the tutorial, I will describe, how you can use CultureInfo as format provider. Have a look at our last Example for this tutorial.
|All times are GMT +5.5. The time now is 11:18.|