By J.V.Ravichandran
Before proceeding with class indexers, let us quickly look at the following piece of code which compares two strings but in a slightly different manner in that each string is scanned into a char variable and then compared. Since each character has to be compared, each character needs to be extracted from the strings. And since, a 'char' ('a') cannot be compared with a string or an array without casting it, the character needs to be first scanned into a 'char' type variable and then compared. The comparison in this example is also based on case i.e. it is case sensitive.
To introduce a little bit of class indexers, I will need to draw attention to the concept of properties of a class. Properties can be understood as attributes of a
class. A class indexer at first look looks like a cross between a constructor and a property. It has the name of a class but is different from the constructor in that it
is followed by the 'this' keyword and a parameter which looks like a subscript out of an array and is completed by a get, let or a set method just like in a property. But
the major attraction of the class indexer is that it can be manipulated just like an array and the major difference between a property and a class indexer is that a property does not have port a 'this' keyword and a class indexer does !
My next example in the following article will fully tackle this glorious extension of the finest of the finer characteristics of OOPS - Class Indexer. The point to note about Microsoft's languages or products is that it has a WYWIWYG(What You Wish Is What You Get !). A seasoned programmer's wishes are nearly always fulfilled if he wishes with a Microsoft's product and Microsoft's claim that the class indexer will fulfill the wishes of such a programmer may well be justified !
//Class that compares two strings and returns
//a message "Yes" on match and "No" on no match
using System;
class compare{
public void comparestr(string s,string s1){
for (int i=0;i<5;i++){
char ch=s[i];
char ch1=s1[i];
if (ch==ch1){
Console.WriteLine("Yes");
}
else{
Console.WriteLine("No");
}
}
}
}
class abc{
public static void Main(){
compare c1=new compare();
compare c2=new compare();
c1.comparestr("c-sharp","C-Sharp");
}
}