There are two main categories of programming languages: one is statically-typed and the other is dynamically-typed. In this C# programming tutorial, we are going to discuss the concept of static typing while working with data types in C#.
What is Static Typing in C#?
In C#, after the declaration of a variable of a specific type, you cannot declare it again. Nor can you store the value of another type into it. That is how static typing works in C#. Consider the following code example:
int val; val = “Hello World!”;
If you try to run the above code snippet, it will not compile and, further, throws an error stating something along the lines of ‘Cannot implicitly convert string to integer’. The solution to this problem is to implicitly convert that type to the given variable type. This is also called casting or type casting.
For instance, there might come a time when you want to pass an integer value to a method that requires a double or long argument. C# provides different ways to convert between different types. They are as follows:
- Implicit conversion
- Explicit conversion
- User-defined conversion
- Conversion with Helper classes
Before we discuss how the various conversion techniques work, however, let’s first briefly learn more about the different data types in C#.
What Data Types are in C#?
In most programming languages, including C#, data types are broadly classified into two categories: primitive and non-primitive.
Primitive data types are predefined in the programming language itself, such as byte, int, float, bool, char, and so forth. On the other hand, non-primitive data types are user-defined types, such as array, class, struct, delegate, and so on.
In the next section, we will look into different methods of typecasting in C#
What are Implicit Conversions?
Implicit conversions are the simplest way to convert one data type into another in C#. It is a type-safe conversion technique that makes sure that no data loss occurs while converting from one type to another. This type of conversion is required when converting a derived class into a base class.
Let’s say we have an integer value and we want to assign that value to a variable of type double. Developers can convert an int value to a double value in C# using the following code example:
int x = 75; double bigger = x;
The above code is an example of implicit conversion in C#. Here, we are storing the value of x to another variable directly. There is no chance of data loss in this case because we are converting a smaller data type to a larger one.
Here is an example of converting a derived class into the base class using C#:
ChildClass child = new ChildClass(); BaseClass base = child;
What are Explicit Conversions in C#?
Explicit conversions are type of casting associated with data loss or failed attempts to convert from one type to another. During the process of conversion from one type to another, if there is a chance of data loss, an explicit conversion is required by the compiler. This technique makes use of a cast operator.
For example, in the example code below, we are converting a higher precision data type into a lower precision data type:
double a = 85.25; int b; b = (int)a;
In this code, (int) is the cast operator. During the process of casting, the value of a is stripped of all digits after the decimal. Hence the value stored in b would be 85.
In the same manner, we can convert a base class into a derived class using cast operator in C#:
ChildClass child = new ChildClass(); BaseClass base = child; ChildClass c1 = (Childlass) base;
Type Conversions with Helper Classes in C#
C# provides a mechanism called Helper classes to convert between different non-compatible data types. The conversion might be, for example, from a string to a number or from a hexadecimal string to a numeric one. As we cannot directly convert one type into another, we require Helper classes to perform the conversion.
The Convert class contains methods to convert a type into another type. You can also use the Parse method to typecast numeric data.
The Parse method is used mostly in cases that require conversion from a string to an integer. It is easy to use and has straightforward syntax.
int x = Int32.Parse(“547”);
In this code, a string can be converted into an integer. The value of x will be an integer value: 547.
Now, let’s look at another method used for typecasting called Convert. The Convert class contains static methods which can be used for conversion from different data types.
Take a look at the following C# code example demonstrating how to use the Convert class:
int num = 80; string s = Convert.ToString(num);
Here, Convert.ToString() is employed to convert a data type to a string type.
It is possible that the conversion from one type to another one could not be performed due to invalid casting or unsupported types. In such cases, the compiler will throw an exception called InvalidCastException.
What is the System.InvalidCastException in C#?
The System.InvalidCastException exception is thrown when the compiler fails to cast a type into another type and hence the casting is unsuccessful. In the case of reference type conversions, the compiler might fail to determine if the casting is valid between the two types. This happens when the source type cannot be converted to the destination type.
For instance, if you try to convert a string value to a DateTime value, your code will run into a problem and the C# compiler will throw an InvalidCastException exception.
Note that the InvalidCastException occurs due to programming errors, so you cannot handle it in the try/catch block; instead, in such cases you would have to eradicate the cause of the error.
Final Thoughts on Type Conversions in C#
In every developer’s life, there may come a time when they have to use typecasting or type conversion in their program. Typecasting and type conversions are an easy task that even novice developers can understand without much effort. However, programmers do need to be aware of a few rules, as outlined throughout this programming tutorial. Typecasting and type conversions help developers keep their application code less prone to errors and easier to maintain. They reduce debugging and development time by identifying errors at compile time.