Sobes.tech
Junior

What types of type casting exist in C#?

sobes.tech AI

Answer from AI

In C#, there are two main types of type casting:

  1. Explicit conversion: Requires the use of the cast operator (type). It is used when the compiler cannot safely perform the conversion automatically, for example, when casting from a base class to a derived class or from a higher precision type to a lower one (e.g., double to int). It can lead to data loss or runtime errors (InvalidCastException).

    // Explicit cast from double to int
    double d = 123.45;
    int i = (int)d; // i will be 123
    
    // Explicit cast of an object to a specific type
    object obj = "Hello";
    string s = (string)obj; // s will be "Hello"
    
  2. Implicit conversion: Performed automatically by the compiler when the conversion is known and safe, meaning no data loss occurs. For example, casting from int to double.

    // Implicit cast from int to double
    int x = 10;
    double y = x; // y will be 10.0
    
    // Implicit cast from a derived class to a base class
    class Base {}
    class Derived : Base {}
    
    Derived derivedObj = new Derived();
    Base baseObj = derivedObj; // Implicit cast
    

Additionally, there are the as and is operators, which are also related to type casting but with specific features:

  • as operator: Performs a cast if possible and returns null if the cast fails. It does not throw an InvalidCastException. It is only used for reference types and nullable types.

    // Using the `as` operator
    object obj2 = "World";
    string s2 = obj2 as string; // s2 will be "World"
    
    object obj3 = 123;
    string s3 = obj3 as string; // s3 will be null
    
  • is operator: Checks whether an object is an instance of a specific type or derived from it. Returns true or false. In recent C# versions, it can be used with pattern matching for simultaneous type checking and casting.

    // Using `is` to check type
    object obj4 = "Example";
    if (obj4 is string)
    {
        // Actions if the object is a string
    }
    
    // Using `is` with pattern matching
    if (obj4 is string str)
    {
        // str is accessible here as a string
    }
    
What types of type casting exist in C#? — C# - sobes.tech