Indexers Vs Properties in C# (C Sharp)Indexers and Properties are instance members of a class. Both have similar purpose but its usage and accessibility is different. This article does a compare and contrast on Indexers and Properties. To understand about these two concepts, a simple example is given below. The example is then followed by the illustration and comparison.
Example: class declareIndexerClass
{ public class
testIndexerClass { //Accessing
Indexer
This example uses both property and indexer. The class declareIndexerClass contains two properties namely sampleProperty and sampleArray. The later is a one dimensional array. sampleProperty has its accessor methods (get and set) defined. Followed by this definition is an indexer which is used to get and set values of sampleArray. Indexer accepts indexVal as parameter and this is used as index to get and set a particular array element. Validation is done to check if the index is valid. If this condition check is not done and an incorrect index is used then IndexOutOfRangeException will be thrown. This situation is avoided using if-else condition checks inside the get and set method of indexer. get method fetches an array element located by specific index and set method sets the specific array element identified by the index. testIndexerClass is another class that has its Main method defined. Inside this method, an instance of declareIndexerClass is created. Using this instance, both the property and the indexer are accessed. Comparison of Property and Indexer: In this section, you will do a comparison of property and indexer using the example discussed above. Property
of a class should have a unique name. Indexer doesnt require a name,
and it is accessed using this. In the above example, sampleProperty
is a property. Indexer is defined using the following line of code: Class
can have any number of properties and each property can have two accessor
methods namely: get access method of property accepts has no parameters. But get access method of indexer accepts the parameters passed along with this pointer. set
access method of property can only use the implicit parameter called value.
Consider the following statement, Property of a class will be accessed as objectname.propertyname. Indexers are accessed only using the object name. In the above example, property is accessed as: sampleObj.sampleProperty
= SAMPLE; This is because
an indexer doesnt have a name and it is defined using this
which refers to the instance directly. In this example, indexers are used
to fetch and store elements of sampleArray. If indexers are not used,
then sampleObj.sampleArray[0] has to be used instead of sampleObj[0] to
access 0th element of the array. public string this[int indexVal] Means that
indexVal is a parameter associated with indexer. Unlike methods where
parameters are included using ( ) brackets, in indexers parameters are
mentioned inside [ ] brackets.
|