Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I think you might be mixing up things. From the examples you gave, I guess you might be confused by event handlers, and the fact that they usually have a method signature along the lines of <code>void Handler(object sender, EventArgs args)</code> where sender might be an instance of say a <code>Button</code>.</p> <p>In OOP types can inherit from other types and you can use instances of inherited types as instances of base types, this concept is called <a href="http://en.wikipedia.org/wiki/Subtype_polymorphism" rel="nofollow">Polymorphism</a>. For instance, the <code>Button</code> class inherits from <code>Object</code>, somewhere up the inheritance chain. You could say that an inherited type is a <em>specialized kind</em> of its base type:</p> <pre><code>class Person { } // Person is our base type class John : Person {} // John is a specialized kind of Person </code></pre> <p>Therefor you could say that when creating an instance of John, that this is also an instance of Person:</p> <pre><code>John john = new John(); Person johnAsPerson = john; // Perfectly fine, makes sense even </code></pre> <p>But not the other way around, because not all people are <code>John</code>, some might be <code>Steve</code> or <code>Mary</code>, some might even just be <code>Person</code>:</p> <pre><code>Person person = new Person(); John john = person; // Won't work </code></pre> <p>In those cases where we <em>know</em> that it's an instance of <code>John</code>, we can tell the compiler "don't worry, I know what I'm doing", and explicitly cast the <code>Person</code> to a <code>John</code>:</p> <pre><code>Foo(new John()); static void Foo(Person person) { John john = (John)person; // We expect it to always be a instance of John // If not, the runtime will throw an exception, that we're trying to do an invalid cast } </code></pre> <p>To be clear, it's important to differentiate between the Type of an instance, and the Type of a variable:</p> <pre><code>string a = "123"; // | |-&gt; I'm an instance of the Type `string` // |-&gt; I'm a variable of type `string`, that points to an instance of type `string` object o = a; // |-&gt; I'm a variable of type `object`, that points to an instance of type `string` </code></pre> <p>The point with event handlers is that they usually provide the sending control instance in the form of its base type <code>Object</code>. The instance of the control is still very much a <code>Button</code>, but we're just looking at it as an <code>Object</code>. Therefor you can cast the <code>Object</code> to a <code>Button</code>.</p>
 

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