If you know each of the types you want to compare with, use the is operator:
if (this is WorldListener) { // ... } else if (this is MasterListener) { // ... }
Alternatively, you can use GetType if you want a little more flexible:
var type = GetType(); // Do some logic on the type to determine what to do next.
However, you must be careful with this approach; it usually indicates a poor design that you need to explicitly check types (since these nice people insist). Instead, it is almost always more appropriate to use polymorphism to delegate the desired behavior to the base class (using a virtual or abstract method in the base class) - this is, after all, what it is intended for!
You can apply polymorphism like this:
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); } }
This will exit [World] Did something! . The advantage of this approach is that if you want to add another type of listener, it is just a matter of defining a new class for it using the corresponding Decorate method; no need to modify the Listener itself.
source share