06 Feb 2024
Type Safety:
Type safety is a fundamental concept in C# and other statically typed languages that ensures that operations performed on variables are valid for their declared types, thus preventing unintended behavior or errors at runtime.
In C#, the compiler checks the types of variables at compile-time to ensure that they are used in a manner consistent with their declared types. This helps catch type-related errors before the program is executed.
Example of Type Safety:
// Type-safe example
int x = 5;
int y = 10;
int sum = x + y; // Type-safe addition of two integers
// The following line would result in a compilation error because of type mismatch
// double result = x + y; // Error: Cannot implicitly convert type 'int' to 'double'
In this example, the addition of two integers (x and y) is type-safe because both variables are of type int. If you attempt to assign the result to a double variable without explicit casting, a compilation error occurs, enforcing type safety.
Casting:
Casting is the process of converting a value from one type to another. In C#, there are two types of casting: implicit casting and explicit casting.
-
Implicit Casting:
-
Implicit casting is performed automatically by the compiler when there is no risk of data loss or loss of precision.
-
It occurs when converting a smaller data type to a larger data type or when converting from a derived class to a base class.
-
Example:
int intValue = 10; double doubleValue = intValue; // Implicit casting from int to double
-
-
Explicit Casting:
-
Explicit casting requires the programmer to specify the type conversion using explicit syntax.
-
It is used when there is a risk of data loss or precision loss during the conversion.
-
Example:
double doubleValue = 10.5; int intValue = (int)doubleValue; // Explicit casting from double to int
-
Example Demonstrating Type Safety and Casting:
class Program
{
static void Main()
{
// Type-safe example
int x = 5;
int y = 10;
int sum = x + y; // Type-safe addition of two integers
// Explicit casting example
double doubleValue = 10.5;
int intValue = (int)doubleValue; // Explicit casting from double to int
Console.WriteLine($"Sum: {sum}");
Console.WriteLine($"Explicit Casting Result: {intValue}");
}
}
In this example, the program demonstrates type-safe addition of two integers and explicit casting from double to int. Type safety ensures that operations are performed consistently with the declared types, and casting allows for converting values between different types when needed.