Search code examples
c#castingimplicitexplicitsender

Different behaviours in cast operations?


Could anyone please explain to me why ,in those two casting scenarios below, the casted variables acts different? While first variable (double initial) preserves its initial value in the first example code, the "sender" object changes its content property value according to the new variable which it was casted into?

1st ex:

double initialValue = 5;

int secValue = (int)initial;

secValue = 10;

Console.WriteLine(initial); // initial value is still 5.

2nd ex:

private void Button_Click(object sender, RoutedEventArgs e)
{
    Button btn = (Button)sender;
    btn.Content = "Clicked"; // "sender" objects content property is also set to "Clicked".
}

Solution

  • This has nothing to do with casting. This is the difference between value types and reference types. int is a value type, Button is a reference type:

    int a = 1;
    int b = a;  // the value of a is *copied* to b
    
    Button btnA = ...;
    Button btnB = btnA;  // both `btnA` and `btnB` point to the *same* object.
    

    Simply speaking, value types contain a value, reference types refer to some object. Illustration:

      a       b      btnA     btnB
    +---+   +---+     |        |
    | 1 |   | 1 |     |        +---------+
    +---+   +---+     |                  v
                      |             +-------------+
                      +-----------> |  The button |
                                    +-------------+
    

    The following question contains a more details explanation of this issue:


    Note, though, that in your first example, you are reassigning the value of secValue. You can do the same for reference types as well:

    b = 2;
    btnB = someOtherButton;
    
      a       b      btnA     btnB
    +---+   +---+     |        |              +-------------------+
    | 1 |   | 2 |     |        +------------> | Some other button |
    +---+   +---+     |                       +-------------------+
                      |     +-------------+
                      +---> |  The button |
                            +-------------+
    

    In your second example, you are simply modifying a property of the button, you are not changing which object the variable points to.