Monday, February 10, 2014

Using C# Properties and Indexers

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.
Let's look at the simplest of properties, which behaves in exactly the same manner as a field.
  1. // Just a normal field for comparison
  2. publicint normalField;
  3. // Now a property
  4. privateint _propertyDemo
  5. publicint PropertyDemo
  6. {
  7.   get
  8.   {
  9.     return _propertyDemo;
  10.   }
  11.   set
  12.   {
  13.     _propertyDemo =value;
  14.   }
  15. }
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.
  1. privateint _month
  2. publicint Month
  3. {
  4.   get
  5.   {
  6.     return _month;
  7.   }
  8.   set
  9.   {
  10.     if((value>=1)&&(value<=12))  
  11.     {
  12.       _month =value;
  13.     }
  14.   }
  15. }
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.
  1. privateint _mySecureID
  2. publicint MySecureID
  3. {
  4.   get
  5.   {
  6.     // Accounts and General Users can read this property
  7.     if((USERGROUP =="accounts")||(USERGROUP =="generalusers"))
  8.       return _mySecureID;
  9.     else
  10.       return0;
  11.   }
  12.   set
  13.   {
  14.     // Only Accounts can write to this property
  15.     if(USERGROUP =="accounts")
  16.       _mySecureID=value;
  17.   }
  18. }
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.
  1. class demoClass
  2. {
  3.  privatestring[] data =newstring[5];
  4.  publicstringthis[int index]
  5.  {
  6.   get
  7.   {
  8.    return data[index];
  9.   }
  10.   set
  11.   {
  12.    data[index]=value;
  13.   }
  14.  }
  15. }
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.
  1. demoClass sample =new demoClass()
  2. sample[0]="This";
  3. sample[1]="Is";
  4. sample[2]="a";
  5. sample[3]="Indexer";
  6. Console.WriteLine(sample[0]);
  7. Console.WriteLine(sample[1]);
  8. Console.WriteLine(sample[2]);
  9. Console.WriteLine(sample[3]);

More Tutorials in C# Programming

  1. What is C#?
  2. Your First Console Application
  3. Data Types, Variables and Casting
  4. Introducing Methods and the Main() Method
  5. Flow Control and Entry Points
  6. Using the Visual Studio Debugger
  7. Using Method Parameters and Return Values
  8. Access Modifiers and Scope
  9. Introducing Classes and Structs
  10. What are Namespaces?
  11. Interfaces and Classes
  12. Conditional Statements
  13. Looping and Iteration in C#
  14. Using Arrays and Lists in C#
  15. Constants and Read Only Variables
  16. Advanced Data Types
  17. Error and Exception Handling in C#
  18. Using Properties and Indexers ⇦ You Are here
  19. Using Recursion in C#
  20. Event Handling and Delegates
  21. Method Overloading and Overriding
  22. C# Operator List
  23. Class Inheritance
  24. Class Abstraction and Encapsulation
  25. Aggregation and Advanced Scope Techniques
  26. Class and Method Attributes Explained
  27. Class Constructors and Destructors
  28. Polymorphism in C#
  29. Boxing and Unboxing Value Types in C#
  30. Operator Overloading
  31. Creating Multithreaded Applications with C#
  32. Unsafe Code Execution in Microsoft .Net
  33. Generic Variables
  34. XML Serialization and Deserialization
  35. C# String Formatting Examples

No comments:

Post a Comment