Properties and Indexers

Properties and Indexers

In C#, properties are used to encapsulate fields or variables and provide a consistent and secure way to access and modify them. Properties are defined with a get and/or set accessor method that allows the value of the property to be retrieved or set respectively.

Here is an example of a property definition:

csharp

Copy code

publicclassPerson { privatestring _name; publicstring Name { get { return _name; } set { _name = value; } } }

In this example, the property Name encapsulates the private field _name. The get accessor retrieves the value of _name, while the set accessor assigns a new value to _name.

Indexers in C# provide a way to access elements in a collection using an index. Indexers are defined like properties, but they include an index parameter. Here’s an example:

csharp

Copy code

publicclassMyCollection { privatestring[] _items; publicstringthis[int index] { get { return _items[index]; } set { _items[index] = value; } } }

In this example, the MyCollection class contains an indexer that allows elements to be retrieved or set using an integer index. The get accessor retrieves the element at the specified index, while the set accessor assigns a new value to the element at the specified index. Indexers can also have multiple parameters, allowing for more complex indexing schemes.

Share this post
[social_warfare]
Members, Constructor and Destructor
OO Concepts

Get industry recognized certification – Contact us

keyboard_arrow_up