Type-safe, Casting, and Conversion in C#.

Introduction

 
In this blog, we will try to understand the type-safety, implicit and explicit typecasting. When we talk about safety, it means that we are trying to prevent some type of accident. In the real world, we have two kinds of people, one who believes in safety and another one is enjoying life. In the same way, we have two types of language one is type-safe another one is not.
 
For example, Javascript is not type-safe. Please check out the below code.
  1. <script>  
  2. var num=5;//numeric  
  3. var str="5";//string  
  4. var value=num+str;  
  5. alert(value);  
  6. </script>  
If we run the above code, the output is 55. Why? Since Javascript is not type-safe, it is allowing set one type of data to another type of data without restriction and this will be type-safe errors. Type safety means preventing these kinds of errors. Type error occurs when the developer unknowingly assigns one data type to another data type. But in C#, it will not allow a developer to set one type of data to another type of data because it is a type-safe language.
 
I am trying to write the same code in C#. Please check the below code and the intelligence from the compiler.
  1. int num = 5;  
  2. string str = "5";  
  3. int value = num + str;  
Please check the below snapshot. Typesafe language is alerting you and it will prevent accidents.
 
 
 
Let's discuss on Casting
 
Please check the below code.
  1. double db = 100.20;  
  2. int num = db;  
Please check the below snapshot. The compiler is alerting that it cannot implicitly convert type double to int.
 
 
 
In case you need to achieve this one you can use convert function and casting. Please check the below code casting. Casting means moving data from one data type to another data type.
 
Explicit type casting
 
The below code refers to the explicit casting, which means we need to specify basically which data type you want to convert.
  1. double db = 100.20;  
  2. int num = (int)db;  
Implicit type casting
 
Implicit casting means from one data type to another data type without giving any type of conversion. In the below code, I am moving the integer value to double data type.
  1. double db = 100.20;  
  2. int num = (int)db;  
  3. db = num;//implicit  
The important point to remember is .NET will allow implicit casting only when there is no data loss. For example, data loss happens when try to move higher value to a lower value.
 
Summary
 
In this blog, we have discussed the Typesafe and casting with a simple program.
Next Recommended Reading Type Casting In C#