Web Design that taps into the haromny and vision of your dreams.

Using C# Properties and Indexers

Properties and Indexers are two important concepts, learn all about them here

Written By on in C#

510 words, estimated reading time 3 minutes.

Properties are the same as fields, however, they can execute code when you access them via getters and setters. This allows for protection of class information and enforcement of business rules.

Advanced C# Programming Series
  1. C# Advanced Data Types
  2. Using C# Properties and Indexers
  3. C# Event Handling and Delegates
  4. Method Overloading and Overriding in C#
  5. C# Class Abstraction and Encapsulation
  6. C# Aggregation and Advanced Scope Techniques
  7. Polymorphism in C#
  8. Boxing and Unboxing Value Types in C#
  9. C# Operator Overloading
  10. Creating Multi-Threading Applications with C#
  11. Unsafe Code Execution in Microsoft .Net

Let's look at the simplest of properties, which behaves in exactly the same manner as a field.

// Just a normal field for comparison
public int normalField;
 
// Now a property
private int _propertyDemo
 
public int PropertyDemo 
{
  get 
  {
    return _propertyDemo;
  }
 
  set
  {
    _propertyDemo = value;
  }
}

You will notice that we declare a private int as well as a public int. The private int _propertyDemo is the field that will hold the data, whereas the public int PropertyDemo is the property that will be used to access the private field. The private and public identification names can be anything you wish, be we recommend that you use a _ (underscore) character as a prefix to denote that it is the private property field.

Properties use the get and set keywords to read and write to the private field. In the get we simply return the value of _propertyDemo in the set we assign the keyword value (which represents the value being passed in) to the private field.

Properties are used to protect input from invalid data, apply business logic or to provide security functions. Let's first have a look at data validation in our property. Let's assume that the value can only be between 1 and 12.

private int _month
 
public int Month
{
  get 
  {
    return _month;
  }
 
  set
  {
    if ((value >= 1) && (value <= 12))  
    {
      _month = value;
    }
  }
}

This will ensure that the value of _month will always be between 1 and 12. If the user of your class passes in a value outside this range it will not be applied.

We can also implement security in the getter and setter. Security will be covered in later tutorials so we will just use verbose methods for this example.

Let's assume that only certain users can assign to the property and different users can read the value.

private int _mySecureID
 
public int MySecureID
{
  get 
  {
    // Accounts and General Users can read this property
    if ((USERGROUP == "accounts") || (USERGROUP == "generalusers"))
      return _mySecureID;
    else
      return 0;
  }
 
  set
  {
    // Only Accounts can write to this property
    if (USERGROUP == "accounts")
      _mySecureID= value;
  }
}

Please Note: This is not a secure code example; it's purely intended to illustrate properties.

Indexers

Indexers, also known as Iterators or Smart Arrays, are very similar to properties, but they allow you to use an index on an object to obtain values. Instead of creating a property name and public/private fields you simply use the this keyword to reference the object itself. Indexers allow you to access data within a class or object by treating it like an array.

class demoClass
{
 private string[] data = new string[5];
 public string this [int index]
 {
  get
  {
   return data[index];
  }
  set
  {
   data[index] = value;
  }
 }
}

In this short example public string this defines the indexer with an integer index. When accessed the code in the get or set executes in the same way as a property.

demoClass sample = new demoClass()
 
sample[0] = "This";
sample[1] = "Is";
sample[2] = "a";
sample[3] = "Indexer";
 
Console.WriteLine(sample[0]);
Console.WriteLine(sample[1]);
Console.WriteLine(sample[2]);
Console.WriteLine(sample[3]);

Last updated on: Friday 23rd June 2017

 

Comments
Francis

Francis

can i ask why is it that the get key word was coded first before the

set key word?

thank you

Reply to Francis
Tim Trott

Tim Trott

Hi Francis,

It really makes no difference on the order, but historically the getter has always appeared before the setter. Anyone know the reason behind this (apart from alphabetical listing!)

Thanks

Reply to Tim Trott
george

george

may be indexing yes but the properties section shouldn't be under the Advanced section. because it is very simple.
also i prefer to use properties names start with capital. in your example "public int propertyDemo" should be "public int PropertyDemo"

george
creator of http://www.sholod.com

Reply to george

 

Leave a Reply

Your email address will not be published.





If you find something abusive or that does not comply with our terms or guidelines please flag it as inappropriate.

Copyright © 2001-2018 Tim Trott, all rights reserved. Web Design by Azulia Designs

This web page is licensed for your personal, private, non-commercial use only.

Disclaimer, Privacy & LegalSitemapContact Me