Difference Between Properties and Indexer in C#
Difference Between Properties and Indexer. Properties and Indexers are the most important concepts in C#. Indexers are like properties. Indexer an object to be indexed in the same way as an array. Indexer modifier can be private, public, protected or internal. Properties are used for encapsulating access to a field of a class. C# properties have to Getand Set accessors
|Identified by its name.||Identified by its signature.|
|Accessed through a simple name or member access.||Accessed through element access.|
|Can be a static or an instance member.||Must be an instance member.|
|A get accessor of a property has no parameters.||A get accessor of an indexer has the same formal parameter list as the indexer.|
|A set accessor of a property contains the implicit value parameter.||A set accessor of an indexer has the same formal parameter list as the indexer, in addition to the value parameter.|
Properties in C#
- Properties are named members of classes, structures, and interfaces. Member variables or methods in a class or structures are called Fields.
- Properties are an extension of fields and are accessed using the same syntax. They use accessors through which the values of the private fields can be read, written or manipulated.
- Properties do not name the storage locations. Instead, they have accessors that read, write, or compute their values.
- For example, let us have a class named Student, with private fields for age, name, and code. We cannot directly access these fields from outside the class scope, but we can have properties for accessing these private fields.
Indexers in C#
- Indexer Concept is object act as an array.
- Indexer is an object to be indexed in the same way as an array.
- Indexer modifier can be private, public, protected or internal.
- The return type can be any valid C# types.
- Indexers in C# must have at least one parameter. Else the compiler will generate a compilation error.