Monday, October 17, 2011

C# and .NET interview questions: - What is the need of Casting in C#? What is casting?

This is one of the typical .NET interview questions and has been asked in many of the mid .NET and c# interviews, also the favorable question of the interviewers where they check your skills on casting. Many of our developer friends who are having 1 to 2 years of experience in development also fail to answer this question.

So, let me explain first explain the need of casting.

Let’s create a small and simple demonstration in order to understand the need of
casting in much better manner.

In order to see it practically just follow the following steps.

Step1: - Create a Console Application for that just open Visual Studio >> go to >> File >> New >> Project >> Windows >> Select Console Application.








Step2: - Now, simply just add the below code snippet in to program.cs file of your Console Application.

static void Main(string[] args)
{
int i = 45.12;
}

In the above code snippet you can see that I have created an “int” variable “i” and we are trying to move data with decimal part in to the ‘int’ data type.
As you know that the “int” data type can only contain positive or negative value in it and not the decimal part.

Now if you try to compile the code you should see the below error message.






In the above error message diagram you can clearly see that the compiler says that it cannot implicitly convert type ‘double to int’ and are you missing a cast.

So how do we solve the above problem, simple by using CASTING.

Casting: - In simple words casting is nothing but converting data of one data type to another data type.

In order that the above code works you need to specify the integer casting as show in the below code snippet.

static void Main(string[] args)
{
int i = (int) 45.12;
}

When you compile the above code snippet you will find that the compilation has been done successfully like below diagram.




Now the next question which will come to your mind , ‘int’ says he will not take decimals and now the above code is compiling and it’s trying to push decimal data in to INT , so what will get stored in to ‘i” variable.

Now if we put a debug point and see the data in add watch as shown in the below images.







You can clearly see that the value of “i” variable is 45. Which means the fraction part has been eliminated: in other words there has been data loss.

In other words when we do casting there can be loss of data.

Following is the video on regular expressions for preparation on .NET: -



Click and view for more c# interview questions and answers

Regards,

View more author’s Most asked c# interview questions

No comments: