Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C# (http://www.go4expert.com/articles/c-sharp-tutorials/)
-   -   C# Formatting & Parsing With ToString, Parse and IFormattable (http://www.go4expert.com/articles/c-sharp-formatting-parsing-tostring-t30021/)

shabbir 5Mar2014 08:56

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.

ToString & Parse Methods



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
Code:

bool bval = true;
string sval = bval.ToString();

On bool variable bval, ToString method has been called, which will return a string containing value ‘True’ because bval had value ‘true’.

Similarly, consider the following lines of code
Code:

string s2val = "false";
bval = bool.Parse(s2val);

Here we are parsing, s2val string that contains ‘false’ into a bool. It will return a bool value containing ‘false’.

Now let us put the above concepts into a working example. Have a look at Example1.

Example1

Code:

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            Console.WriteLine("Formatting & Parsing Example using ToString & Parse Methods\n");
            bool bval = true;
            string sval = bval.ToString();

            if (sval.ToLower() == "true")
                Console.WriteLine("formatting successful");
            else
                Console.WriteLine("formatting unsuccessful");

            string s2val = "false";
            bval = bool.Parse(s2val);

            if (bval)
                Console.WriteLine("Parsing Unsuccessful");
            else
                Console.WriteLine("Parsing successful");
            Console.ReadLine();
        }
    }
}

In Example1, first of all we declared a bool variable ‘bval’ and initialized it to true. We then declared a string sval and called ToString method on ‘bval’ which will return a string containing value ‘True’. Note here, when you called ToString on a bool that contains ‘true’ it returned a string ‘True’ with capital ‘T’ that’s internal behavior of ToString method of the bool type. Next, in order to check that whether our formatting was successful or not, we compared our sval value to a string literal ‘true’ but before that we converted sval to lower to make sure that comparison is successful if the string contains ‘true’. If the sval is equal to ‘true’ it means are formatting is successful and that’s what we displayed and if otherwise, we have displayed that formatting is unsuccessful.

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.

Output1

http://imgs.g4estatic.com/c-sharp/fo...ng/output1.png

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.

http://imgs.g4estatic.com/c-sharp/fo...ing/output.png

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.

Example2

Code:

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            Console.WriteLine("Parsing using TryParse method\n");
 
            bool bval;
            string s2val = "fals";
            bool.TryParse(s2val, out bval);

            if (bval)
                Console.WriteLine("Parsing successful");
            else
                Console.WriteLine("Parsing unsuccessful");
            Console.ReadLine();
        }
    }
}

Here we have used TryParse method for coverting string s2val that contains value ‘fals’ which cannot be parsed to bool. Note here that we have second parameter in TryParse method that is ‘out bval’ which is actually tells the compiler that store the result of the parsing in this variable. Therefore, in the next line we checked that if the bval is true, display that parsing is successful to output screen, otherwise display that parsing was unsuccessful. And off course in this case, TryParse will return false therefore the result will be the latter one. The output of Example2 is as follows.

Output2

http://imgs.g4estatic.com/c-sharp/fo...ng/output2.png

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.
Code:

double dval = double.Parse("4.563", CultureInfo.InvariantCulture);
string sval = 4.563.ToString(CultureInfo.InvariantCulture);

Formatting Using Format Providers



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.
Code:

public interface IFormattable
{
    string ToString(string format, IFormatProvider formatProvider);
}

Here the first argument in the ToString method is the string format which shows the property of the string that should be formatted and the second argument is the formatProvider which actually formats the first argument.

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.

Example3

Code:

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            NumberFormatInfo format = new NumberFormatInfo();
            format.CurrencySymbol = "Rs.";

            Console.WriteLine(5000.ToString("C", format));

            format.CurrencySymbol = "$$ ";
            Console.WriteLine(5000.ToString("C", format));

            Console.ReadLine();
        }
    }
}

Here we have use NumberFormatInfo type which acts as a format provider for the ToString method. We specified its CurrencySymbol property some value i.e. “Rs.” in this case. We then called ToString method on an integer 5000, the first argument of the ToString method is “C” which means that return a string in which the integer is represented in the format of a currency and second argument is the format, which tells that the format of the currency should have a symbol ‘Rs.’ appended before the actual amount.

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

Output3

http://imgs.g4estatic.com/c-sharp/fo...ng/output3.png

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,
Code:

Console.WriteLine(5000.ToString("C",null));
It will fetch the default currency format depending upon the current culture or region in which your application is being run. Similarly, if you write
Code:

Console.WriteLine(15.6.ToString("F5",null));
We are telling the compiler that convert 15.6 into string and modify the term after the decimal to 5 decimal points.

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.
Code:

Console.WriteLine(5000.ToString("C"));
Console.WriteLine(15.6.ToString("F5"));

As usual, we will take help of an example to explain how they work and is there any difference between them. Have a look at the Example4 of this article.

Example4

Code:

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {

            Console.WriteLine(5000.ToString("C",null));

            Console.WriteLine(15.6.ToString("F5",null));

            Console.WriteLine("\nWhen we dont pass null ...\n");
            Console.WriteLine(5000.ToString("C"));

            Console.WriteLine(15.6.ToString("F5"));

            Console.ReadLine();
        }
    }
}

Here in the first two lines we have passed the second parameter as null, and then in the next two statements we didn’t pass any parameter. In both the cases: with or without the format provider being passed as null, the default format provider will be used i.e. CultureInfo.CurrentCulture. The output of the first two lines and the last two lines will be same. Compile the code and it should have output similar to Output4.

http://imgs.g4estatic.com/c-sharp/fo...ng/output4.png

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.

Example5

Code:

using System;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Globalization;

namespace CSharpTutorial
{
    class Program
    {
        public static void Main()
        {
            CultureInfo UnitedKingdom = CultureInfo.GetCultureInfo("en-GB");
            Console.WriteLine(5000.ToString("C",UnitedKingdom));
            Console.ReadLine();
        }
    }
}

Here we have a CultureInfo object ‘UnitedKingdom’ and we set it to United Kingdom’s culture by calling GetCultureInfo static method of the CultureInfo class and then passed “en-GB” to it where GB refers to Great Britain. As we have mentioned that CultureInfo object can also be passed as format provider which is second argument of the ToString overloaded method. Now, since the culture is United Kingdom, therefore the currency symbol of this culture will also be passed to the ToString method which will be pounds in this case. Therefore when you compile the code in Example5, you will see that there is a pound sign appended before the amount as shown in the output.

Output5

http://imgs.g4estatic.com/c-sharp/fo...ng/output5.png


All times are GMT +5.5. The time now is 14:47.