13&14. Indexers and Inheritance


Indexers are a new concept in C#. Indexers enable a class object to function as an array. Implementing indexers is similar to implementing properties using the get and set functions. The only different is that when you call an indexer, you pass an indexing parameter. Accessing an indexer is similar to accessing an array. Indexers are nameless, so the this keyword declares indexers.


I just said that after defining indexers, a class object could be treated as an array. What does that mean? To explain, I‘ll show you an example using the class called my class. The way you treat an instance of myClass now is like this:

 

myClass cls = new myClass();
cls.MaleGender = true;

After defining an indexer in myClass, you could treat an instance of it as if it were an array:

myClass cls = new myClass();
cls[0].MaleGender = true;
cls[1].MaleGender = true;

You define indexer by using the this keyword as if were an array property of type object.
Listing 36 shows the indexer signature of my class.

Listing 36. Indexers of myClass

public object this[int index]
{
get
{
if (! ValidIndex(index))
throw new Exception("Index out of range.");
else
return MaleGender(index).Value;
}
set
{
if (!ValidIndex(index) )
throw new Exception("Index out of range.");
else
MaleGender(index).Value = value;
}
}

 

 

Inheritance


Inheritance is one of the main features of an object-oriented language. C# and the .NET class library are heavily based on inheritance. The telltale sign of this is that all .NET common library classes are derived from the object class, discussed at the beginning of this article. As pointed out, C# doesn’t support multiple Inheritance. C# only supports single inheritance; therefore, all objects are implicitly derived from the object class.

Implementing inheritance in C# is similar to implementing it in C++. You use a colon (:) in the definition of a class to derive it from another class. In listing37, BaseClassB, which later accesses the BaseClassA method in the Main method.

Listing 37. Inheritance example

using System;

// Base class A
class BaseClassA
{
      public void MethodA()
      {
      Console.WriteLine("A Method called");
      }
}

// Base class B is derived from Base class A
class BaseClassB:BaseClassA
{
public void MethodB()
{
Console.WriteLine("B method called");
}
}
class myClass
{
static void Main()
{
// Base class B
BaseClassB b = new BaseClassB();
// Base class B method
b.MethodB();
// BaseClassA Method through BaseClassB
b.MethodA();
}
}

 Note: The below sections will be updated in next version.


Previous           Next