Explicit conversion

When the compiler is not able to implicitly change the type of variables, but we still want the conversion to happen, we need to explicitly instruct the compiler to convert the value. This is referred to as explicit conversion.

There are two ways to do explicit conversion in C#:

  • Using a type cast operation: In this, we use the base data type to instruct the compiler to do explicit conversion. For example, for the code implementation that we were trying in the preceding example, the following would be the syntax:
float k = 100.0F;
int j = (int)k;

In the preceding code, we are explicitly telling the compiler to do type conversion by using the int class conversion before the float variable.

  • Using the Convert class: C# provides us with the Convert class, which we can use to do type casting between multiple data types. If we were to use the Convert class instead of the int keyword, the following would be the syntax:
float k = 100.0F;
int j = Convert.ToInt32(k);

Convert class can be used for type casting among different data types. Please refer to the following screenshot to get an idea of the different options that are available in the Convert class. Depending on the usage, we can use the appropriate method in the Convert class:

Hence, the overall implementation of the program will look like this:

float k = 100.67F;
int j = (int)k;
int a = Convert.ToInt32(k);
Console.WriteLine(j);
Console.WriteLine(a);
Console.ReadLine();

Now, let's try to run this program to see the output it gives:

It implies that when we use the type cast keyword, that is, (int)k, the compiler tried to extract the integer component from the float variable, k, which turned out to be 100.

On the other hand, when we used the Convert class, that is, Convert.ToInt32(k), it tried to extract the nearest integer to the float variable, k, which turned out to be 101. This is one of the key differences that developers need to be aware of while deciding between using type casting and the Convert class. 

While we are looking at explicit type conversions, we need to be aware of two helper methods that help us do conversions:

  • Parse
  • TryParse

Both the Parse and TryParse methods are used to convert string into a different data type. However, there is a slight difference in the way invalid case exceptions are handled. Let's look at the following example to see how they work and the difference between them:

string number = "100";
int num = int.Parse(number);

In the preceding example, we have declared a string object and have assigned it a value of 100. Now, we are trying to convert the value into an integer using the Parse method. When we run the program, we see the following output:

It implies that the parse method converts the string into its integer equivalent and assigns the value to another variable, num

Now, let's suppose the value in the number is 100wer. Now, it's evident that the value in the number string cannot be converted into int because it has some characters that cannot be categorized in an integer object. When we run this program, we get the following exception:

To avoid such situations, we use TryParse. In TryParse, CLR tries to convert the string object into the specified data type. However, if the conversion returns an error, TryParse returns false or, in other words, the conversion failed. In other cases, it returns true. Hence, if we were to write the same implementation with TryParse, we would do the following:

 string number = "100wer"; 
int num;
bool parse = int.TryParse(number, out num);
if(parse)
{
Console.WriteLine(num);
}
else
{
Console.WriteLine("Some error in doing conversion");
}
Console.ReadLine();

In the preceding program, we have declared a variable of the string type and we are using TryParse to convert this value into a variable of the int type. We are checking whether the conversion is a success. If it's a success, we print out the number and in other cases, we print a statement to show that there was an error during the type conversion. When we run the program, we get the following output:

As we see from the output, the compiler tells us that there was an error doing the TryParse; however, it does not throw an exception in the application as opposed to the Parse method, which threw an invalid case exception in the same scenario.

In the next section, we will do a quick recap of encapsulation, which we covered in Chapter 3Understanding Object-Oriented Programming, and we'll see how to implement properties for class member variables objects, allowing us to consume them without worrying about the hidden complexities.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.51.157