Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is compile-time legal. You can write code to cast an object to a Button. At runtime, if the object <em>is not</em> a Button, this will throw an invalid cast exception. This will happen in either of your code snippets.</p> <p>What you might instead be thinking about is an event handler </p> <pre><code>protected void saveButton_Click(object sender, EventArgs e) { Button saveButton = (Button)sender; } </code></pre> <p>This is not the same as your snippet. You didn't create <code>sender</code>, it was passed to you. It was passed as an object. Via the code, you are asserting that you know that at runtime, <code>sender</code> is <em>really</em> a Button. You're telling the compiler to allow you to treat it as one, and the compiler is going to let you.</p> <p>If it turns out you are <em>wrong</em>, you will run into the same runtime exception mentioned above.</p> <p>Put it another way. Say you have this snippet.</p> <pre><code>string foo = "FOO"; object obj = foo; string bar = (string)obj; Button baz = (Button)obj; </code></pre> <p>All of this is compile-time legal. Line 4 will blow up at runtime. You create a string, you create a variable that references the string <em>as</em> an object, you create another variable where you cast the object reference to string, and the fourth line, you try to cast to <code>Button</code>. Line 2 works because you can treat any class or struct as an object. Line 3 works because the object really <em>is</em> a string. Line 4 will obviously not work, <code>"FOO"</code> is not a Button.</p> <pre><code>Button button = new Button(); object sender = button; Button button2 = (Button)sender; </code></pre> <p>Naturally, this works. <code>sender</code> is a Button. Now relate it back to the event model. The handler expects to receive an object via the parameter. The invocation of the handler is <em>actually</em> sending a Button. As a developer, you know this, so you tell the compiler (via the cast) to treat the object as a Button instead. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload