Click here to Skip to main content
15,879,051 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What are the main differences between typecasting and boxing ,unboxing??
Posted

1 solution

Typecasting is a conversion of an expression to a given type, provided that the types are derived from each other, or a suitable conversion method exists. For example, an integer value can be cast to a double, and vice versa:
C#
int i = 999;
double d = 123.456;
i = (int) d;
d = i; // Implicit cast
Or
C#
private void myButton_Click(object sender, EventArgs e)
    {
    if (sender is Button)
        {
        Button b = (Button) sender;
        }
    }
Or
C#
foreach (Control c in Controls)
    {
    if (c is TextBox)
        {
        TextBox tb = (TextBox) c;
        }
    }

You cannot use casting to change between types where there is no defined conversion or relationship.

Boxing and unboxing are the process of "containing" a Value type (such as a integer, or struct) within a Reference type transparently so that it can be used as a reference. This is a bit complicated to explain, so have a look here: Using struct and class - what's that all about?[^] - there is a section on Boxing and what / why it is neccessary.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900