Hi,
We all know about class indexers. Well you can
also have indexers in interfaces.
Interface indexers
differ from class indexers in the following ways :-
- Interface accessors do not use modifiers.
- An interface accessor does not have a body.
- The purpose of the accessor is to indicate whether
the indexer is read-write, read-only, or write-only.
The following is an example of an interface
indexer:
1. Open a new console project. 2. Create two
interfaces i.e. Interface1 and Interface2 (as shown below in the code). 3.
Implement the indexer in each of the interfaces as shown below. 3. Create a class
called as MyClass(as shown below) which implements these two
Interfaces.
Code :
class
MyClass:Interface1,Interface2 { private
int[] ArrayofStrings=new int[100]; public
MyClass() { }
public int this[int
index] //
Interface1 { get { return
ArrayofStrings[index]; } set { ArrayofStrings[index]=value; } } string
Interface2.this[int
index] { get { return
ArrayofStrings[index].ToString() + "
String"; } } }
public class
MainClass { public static void
Main() { MyClass o = new
MyClass();
o[1] =
1; //
interface1
Console.WriteLine(((Interface2)o)[1].ToString()); //
Interface2
Console.ReadLine(); } }
public interface
Interface1 { int this[int
index] { get; set; } }
public interface
Interface2 { string this[int
index] { get; }
}
You will notice that this class has two indexers
one coming from the Interface1 and other coming from Interface2. Indexer
function for Interface1 has the access modifier as "public" whilst the indexer
for Interface2 is private. Since the access modifier for indexer of
Inferface1 is public you can access it directly from the main as you would have
accessed any other class indexer.
But you will notice that along with indexer for
Interface1 you can also access the indexer for interface2 by type casting
because the Interface2 is public.
Hence in this way you can have multiple
indexers in a class using Interface Indexers.
-- Please post your queries and comments for my
articles in the usergroup for the benefit of all. I hope this step from my end
is helpful to all of us.
Regards,
Namratha
(Nasha)
|