Type Casting in C#

Introduction

We have already discussed type casting in JavaScript and Integer class used for type casting in Java. In this tutorial you will learn about type casting in C#.

Type Casting in C#

Type casting in other words also called type conversion is an important part of programming logic. Especially when we have to pick data from outsourcing, and we don’t know, in what form data is.

Like in many programming contests we have to get data from file and after performing operation put it back on the file so the thing is when we get data from file it is usually in the form of string and what if it is actually an integer data or integer array of char array or some other type so to solve problems like that type conversion is used.

The main example of it is while using C# window desktop forms or web forms when we input some data in the textbox and try to get it in C# then we see that it is in the form of a string and if we want to get integer data we have to convert the data receive from input box.

  • So to get started, we have to start Visual Studio.
  • Create a new project.
  • Select Visual C# Console Application this time.
  • And press Ok.

Now first let me clear one thing that string can b change into int, long, double, float but not in char. It is because char contain only one character and the string is a combination of characters.

String to Int

Now Let suppose we have an integer value stored in string, and we want to add 3 in it then it is not possible to string will not be added to other string it has a built-in function concat( ) which concatenate one string with other, but we want to add 3 in that series then first we have to convert it to int and then add the number in it:

As same, we now again convert that int into string

 

 String to integer array

If we have a string value, and we want to convert it into the array so that we do something with each value separately then we have to convert it into an int array.

Convert Long to int

Convert double to int

Convert float to int

Convert char to int

Convert string to int

Convert int to char

Convert long to char

Convert int to string

Convert string to char array

A complete code where I write all these and build the project, and there is no error, and it builds successfully. So these are very important and use full, and we need them on many time where we have to convert from one type to another.

 

Output:

type casting in c# output
type casting in c# output