Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>If you know each of the types you want to compare against, then use the <code>is</code> operator:</p> <pre><code>if (this is WorldListener) { // ... } else if (this is MasterListener) { // ... } </code></pre> <p>Alternatively, you could use <code>GetType</code> if you want a little more flexibility:</p> <pre><code>var type = GetType(); // Do some logic on the type to determine what to do next. </code></pre> <p>You should be careful with this approach, however; it's generally indicative of bad design that you need to explicitly check for types (as these <a href="http://www.antiifcampaign.com/" rel="nofollow noreferrer">lovely people</a> insist). Instead, it's almost always more appropriate to use polymorphism to delegate the desired behaviour to the base class (using a virtual or abstract method in the base class) – this is, after all, what it's designed for!</p> <p>You might apply polymorphism something like this:</p> <pre><code>static class Program { static void Main(string[] args) { Listener listener = new WorldListener(); listener.DoSomething(); } } abstract class Listener { public void DoSomething() { var output = Decorate("Did something!"); ConsoleWrapper.WriteLine(output); } protected abstract string Decorate(string input); } class WorldListener : Listener { protected override string Decorate(string input) { return string.Format("[World] {0}", input); } } class MasterListener : Listener { protected override string Decorate(string input) { return string.Format("[Master] {0}", input); } } </code></pre> <p>This will produce the output <code>[World] Did something!</code>. The advantage of this approach is that if you ever want to add another type of listener, it's simply a matter of defining a new class for it with the appropriate <code>Decorate</code> method; there's no need to modify <code>Listener</code> itself.</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. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      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