Drop Down MenusCSS Drop Down MenuPure CSS Dropdown Menu

Monday 17 April 2017

What is type safety in C# .net

What is type safety in C# .net

When reading about advantages of using generics, you will come to know you can write type safe collections and these are the collections which avoids boxing and un boxing.
After reading such statements if you are getting questions on type safety, then you are in the right place to understand about type safety concept.

What is type safety in .net?
Type safety prevents assigning a type to another type when are not compatible.
public class Employee{}

public class Student{}
In the above example, Employee and Student are two incompatible types. We cannot assign object of employee class to Student class variable. If you try doing so, you will get a error during the compilation process.  

Cannot implicitly convert type 'Program.Employee' to 'Program.Student'.

As this type safety check happens at compile time it's called static type checking.
public class Employee {}
public class Engineer : Employee {}
public class Accountant : Employee {}

public static void Main(string[] args)
  {
   Accountant accountant = new Accountant();
   Engineer engineer = (Engineer)(accountant as Employee);
  }
In the above example, Engineer and Accountant class derives from the same Employee base class. When tried to type cast object of Accountant class to Engineer class variable, it throws System.InvalidCastException at runtime:

Unable to cast object of type 'Accountant' to type 'Engineer'.

Above type checking happens at runtime, hence it is called runtime type checking.

When does the type safety check happens and who ensures the type safety in .net?

As discussed type safety check happens both at Compile time and at run time. Compiler will do the compile time type safety check and CLR will do the runtime safety check.

How type safety checks makes developers life easy?

The advantages type safety are pretty straight forward.
At compile time, we get an error when a type instance is being assigned to an incompatible type; hence preventing an error at run time. So at compilation time itself, developers come to know such errors and code will be modified to correct the mistake. So developers get more confidence in their code.
Run time type safety ensures, we don't get strange memory exceptions and inconsistent behavior in the application.

No comments:

Post a Comment