Indexer:
- The new concept in C# it is an object that acts as an array
- It is an object that is to be indexed as an array
- Indexer modifier can be private, protected, public or internal
- The return type can be any valid C# data types
- Indexers in C# must have atleast one parameter
- Indexers are also known as smart arrays
- Ref and Out parameters must not be specified
- C# can overloaded just like member functions
- Indexer cannot be static
Syntax:
<modifier> <return type> this [argument list]
{
get
{
// Get codes goes here
}
set
{
// Set codes goes here
}
}
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IndexerDemo
{
class ParentClass
{
private string[] range = new string[5];
public string this[int index]
{
get
{
return range[index];
}
set
{
range[index] = value;
}
}
}
class ChildClass
{
static void Main(string[] args)
{
ParentClass pc = new ParentClass();
pc[0] = "Mandala";
pc[1] = "Vivek";
pc[2] = "Ananda";
pc[3] = "Swamy";
pc[4] = "MVS";
for (int i = 0; i < 5; i++)
{
Console.WriteLine(pc[i]);
}
}
}
}
Indexer and Inheritance
Just like other class members the indexers also can be inherited.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IndexerDemo
{
class IndexerClass
{
private string[] range = new string[5];
public string this[int index]
{
get
{
return range[index];
}
set
{
range[index] = value;
}
}
}
class IndexerDemo1 : IndexerClass
{
class IndexerTest
{
static void Main(string[] args)
{
IndexerDemo1 id = new IndexerDemo1();
id[0] = "Mandala";
id[1] = "Vivek";
id[2] = "Ananda";
id[3] = "Swamy";
id[4] = "MVS";
for (int i = 0; i < 5; i++)
{
Console.WriteLine(id[i]);
}
}
}
}
Indexers can be overridden in the derived class but you must use the virtual and override keywords in order to override the indexer in the derived clas
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IndexerDemo
{
class BaseClass
{
private string[] b = new string[5];
public virtual string this[int index]
{
get
{
return b[index];
}
set
{
b[index] = value;
}
}
}
class DerivedClass:BaseClass
{
private string[] d = new string[10];
public override string this[int index]
{
get
{
return d[index];
}
set
{
d[index] = value;
}
}
}
class IndexerTest
{
static void Main(string[] args)
{
BaseClass dc = new DerivedClass();
dc[0] = "12";
dc[1] = "23";
dc[2] = "34";
dc[3] = "45";
dc[4] = "56";
for (int i = 0; i < 5; i++)
{
Console.WriteLine(dc[i]);
}
}
}
}
Abstract Indexers
The Indexers in the class must be declared by the keyword Abstract.The abstract indexer does not contain any code.If the indexer contains only set or get then the derived class can implement only the set or get.
Example:
Sadiqullah GhaniPosted Dec 4, 2018, 12:54 AM
THINK SO MUCH AND IT IS SO HELPFUL ( THINK AGAIN )