6.4. The as Operator

Listing 6.14 was created from Listing 6.13. The main() method has been changed to demonstrate casting in interfaces. You will notice that for each iteration the array object is checked to determine whether it's of type IRichLife. If it is of type IRichLife, it is then cast to that interface.

As you can see, the code checks the type of the object twice. The first time is in the operator, and the second is during the cast. Doing this several times in a loop is wasteful. C# has the as operator, which lets you reduce the number of type checks.

Listing 6.14. Casting in Interfaces (C#)
using System;
namespace Interfaces {
  class RichMan : IRichLife {
    protected string name;

    public RichMan(string name) {
      this.name = name;
    }
    public void Birth() {
      Console.WriteLine("Birth of {0}",this.name);
    }
    public void Death() {
      Console.WriteLine("Death of {0}",this.name);
    }
    public void Happy() {
      Console.WriteLine("{0} is happy",this.name);
    }
    public void Sad() {
      Console.WriteLine("{0} is sad",this.name);
    }
    public void BuyMansion() {
      Console.WriteLine("{0} buys a mansion",this.name);
    }

    static void Main(string[] args) {
      RichMan[] riches = new RichMan[3];
      riches[0] = new RichMan("Bill Gates");
      riches[1] = new RichMan("Larry Ellison");
      riches[2] = new RichMan("Scott McNealy");
      foreach (RichMan d in riches) {
        if (d is ILife) {
          ((IRichLife)d).Happy();
        }
      }
    }

  }
}

Using the as operator, Listing 6.15 shows that the type checking has been reduced to only once instead of twice.

Listing 6.15. Using the as Operator (C#)
using System;
namespace Interfaces {
  class RichMan : IRichLife {
    protected string name;

    public RichMan(string name) {
      this.name = name;
    }
    public void Birth() {
      Console.WriteLine("Birth of {0}",this.name);
    }
    public void Death() {
      Console.WriteLine("Death of {0}",this.name);
    }
    public void Happy() {
      Console.WriteLine("{0} is happy",this.name);
    }
    public void Sad() {
      Console.WriteLine("{0} is sad",this.name);
    }
    public void BuyMansion() {
      Console.WriteLine("{0} buys a mansion",this.name);
    }

    static void Main(string[] args) {
      RichMan[] riches = new RichMan[3];
      riches[0] = new RichMan("Bill Gates");
      riches[1] = new RichMan("Larry Ellison");
      riches[2] = new RichMan("Scott McNealy");
      foreach (RichMan d in riches) {
          IRichLife life = d as IRichLife;
        if (d != null ) {
          life.Happy();
        }
      }
    }

  }
}

There is no as operator in Java, and therefore you must do the type checking twice in the for loop.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.33.87