Author - StudySection Post Views - 39 views
Typecasting

Object Typecasting

Introduction:
Object Typecasting is a process of converting one data structure into another. The type system is categorized into 2 types, primitives and references.

Primitive types are also known as value types, which means a variable contains the value itself. Most simply type data structure would look like this.
figure
In this figure, we can see that primitive data types are stored inside stack memory and the variables point to a memory location. The variable value is placed next to the variable label in memory.

On the other hand, reference types hold reference or address of the object data, however, that address binding with the label of variable is inside the stack memory, opposite to this variable data is stored inside Heap memory.
typecasting figure1

General Typecasting Equation :

typecasting figure2
This is an object instantiation equation or statement. We have an object of type A having a name or label on it of B.
While typecasting, there are some sets of rules that must be followed, to ensure a successful conversion. Below we are discussing them.

Type Casting Rules:

  1. Compile-time checking 1:
    Type of “D” (refers to the General typecasting equation) and “C” must have some relation in between them. Either child to parent or parent to child or must be of the same type, otherwise, we will get a compile-time error.
    Case 1.
    Object o = "Hello World";
    StringBuilder sb = (StringBuilder)o;

    This code will compile successfully. The object is the topmost class or parent of all types. A string of data can easily hold an Object type.
    After that, object and StringBuilder have a parent/child relationship, however, to convert from parent to child type, we need to explicitly mention the typecasting.
    Case 2.
    string s = "Hello World";
    StringBuilder sb = (StringBuilder)s;

    This code will raise a compile-time error in the second line, where we are explicitly converting a string to the StringBuilder type. There is no relationship between string and StringBuilder type.
    Error description :
    Compile Time Error: Cannot convert type ‘string’ to ‘System.Text.StringBuilder
  2. Compile-time checking 2:
    “C” must be either the same or derived/child type of “A”, otherwise we will get a compile-time error.
    Case 1.
    Object o = "Hello World";
    StringBuilder sb = (StringBuilder)o;

    This code will compile successfully.
    Case 2.
    Object o = "Hello World";
    StringBuilder sb = (string)o;

    The string is not a derived class of StringBuilder and not the same at all, so this code fails to follow rule Compile-time checking 2. Consequently, it will raise a compile-time error.
    Error description:
    Compile Time Error:
    Cannot implicitly convert type ‘string’ to ‘System.Text.StringBuilder’
  3. Runtime checking:
    Type of “D” must be either the same or derived type of “C”, otherwise, we will get a runtime exception,
    Case 1.
    Object o = "Hello World";
    StringBuilder sb = (StringBuilder)o;

    This code will compile with no errors. However, when we try to run it, it will throw a runtime exception.
    At runtime “o” will be of string type, which means, when the runtime environment will execute a second statement, it has to convert a string type variable to a StringBuilder type and we have already seen that there is no any relationship between them.
    Error Description:
    Runtime Exception: System.InvalidCastException
    Unable to cast object of type ‘System.String’ to type ‘System.Text.StringBuilder

    Case 2.
    What do you think, will the following code snippet compile and run without any issue.
    Object o = "Hello World";
    Object o1 = (string)o;

    At runtime, o will be of type string the same as “string”, resulting in a successful type conversion and the program runs smoothly.

    Let’s revise these rules by a quick example:
    Question1: an object is created using the following statement
    Base2 b = new Dev4();
    This diagram shows the sample class hierarchy. We will follow this to answer the questions.
    figure3
    Try to answer the following, while typecasting object “b” if they follow all of the 3 type casting rules, if not mention error/exception details.

    1. Object o = (Base2)b;
    2. Object o = (Base1)b;
    3. Object o = (Dev3)b;
    4. Base1 b1 = (Base1)b;
    5. Base1 b1 = (Dev4)b;
    6. Base1 b1 = (Dev1)b;

    Answers :

    1. Correct Statement.
    2. Raised compile-time error: Cannot convert type ‘Base2’ to ‘Base1’. It implies that there is no direct relationship between Base2 and Base1.
    3. Raised Runtime-Exception error: The statement will compile without any error, yet, it throws a runtime error. Unable to cast object of type ’Dev4’ to type ‘Desc3’.
      Explained:
      Referring to our primary equation, we are calling a constructor of type Dev4 and assigning the instance into a Base2 type object. It means at runtime, we will have an object of Dev4 and in the 2nd statement, we are typecasting it into Dev3. It is evident from the graphic that Dev3 and Dev4 do not have any parent-child relationship between them.
    4. Raised compile-time error: Inconvertible type casting ‘Base2’ to ‘Base1’. Base2 and Base1 do not have any relation between them.
    5. Raised compile-time error: Incompatible type ‘Dev4’ to ‘Base1’. Assignment of ‘Dev4’ to ‘Base1’ is incompatible due to the absence of the necessary relation.
    6. Raised compile-time error: Inconvertible type ‘Dev1’ to ‘Base2’. Converting ‘b’ to ‘Dev1’ is not allowed.

    More examples:

    In this section, we will talk about the effect of typecasting on method resolutions
    Case 1:
    Consider following class hierarchy. There is a class P and its child class C. Note they have their methods.
    class P
    {
    public void m1()
    { }
    }
    class C : P
    {
    public void m2()
    { }
    }

    Now, Inside the main method, we write this code :
    class Program {
    static void Main(string[] args) {
    P p = new C();
    p.m1();
    p.m2();
    }
    }

    Will this code compile?
    The answer is No, Because, parent references can be used to hold child objects, but by using that reference, we can’t call child-specific methods and we can call only methods present inside parent class.

    Due to this, we will get a compile-time error
    ‘P’ does not contain a definition for ‘m2’ and no accessible extension method ‘m2’ accepting a first argument of type ‘P’ could be found.
    Case 2:
    Here we have almost the same code as in the previous case. However, the only difference is we have overridden the method inside the child class.
    class Animal
    {
    //Animal Class
    public virtual void Sound()
    {
    Console.WriteLine("Generic Animal Sound");
    }
    public void Walk()
    {
    Console.WriteLine("Generic Animal Walking");
    }
    }
    class Monkey: Animal
    {
    //Monkey Class
    public override void Sound()
    {
    Console.WriteLine("Monkey Sound");
    }
    }
    class Program
    {
    static void Main(string[] args)
    {
    Monkey m = new Monkey();
    m.Sound();
    // Output: Monkey Sound
    ((Animal)m).Walk();
    // Output: Generic Animal Walking
    ((Animal)m).Sound();
    // Output: Monkey Sound
    }
    }

It is reasonable behavior that we get output as “Monkey Sound” from a Sound method of Monkey, similarly, it is also normal to get “Generic Animal Walking” output from the Walk method because we typecast the Monkey object to Animal type.
Although, by calling the Sound method, in general, we should get an output of “Generic Animal Sound”, but we got “Monkey Sound”. This is because of the Overriding process, the Sound method of the Animal class got overridden by the Sound Method of the Monkey class.
Method Overriding is a runtime process, which means method resolution at runtime will be based on the type of runtime object.
Here, at runtime, the object is of type Monkey, consequently, this output.

Microsoft Windows 10 is a widely used operating system in computers all over the world. If you have skills in Microsoft Windows 10 then you can get a Windows 10 Certification from StudySection which can help you in getting hired. A beginner level certification exam for newbies and an advanced level certification exam for experts is available on StudySection.

Leave a Reply

Your email address will not be published. Required fields are marked *