Friday, October 7, 2011

properties and indexers in c#

Properties:
Properties are extensions to fields. properties are called smart fields. There are two accessors get and set. get is used to retrieve the value where as set is used
to assign the value to that property. A property that contains get accessor only is called read only property, property that contains set accessor only is called write only property. get accessor doesn't accept any parameter, set accessor contains an implicit parameter called value.
Example:

/* Property Example */
using System;
namespace ProjectOne
{
public class PropertyExample
{
int testValue;
public int testProperty
{
get
{
return testValue;
}
set
{
testValue = value;
}
}
}
class Program
{
static void Main(string[] args)
{
PropertyExample PE = new PropertyExample();
PE.testProperty = 200;
Console.Write("{0}", PE.testProperty );
Console.Read();
}
}
}

Indexers:
Indexers treat objects as an array. indexers are called smart arrays.
Example:

/* Indexer Example */
using System;
namespace ProjectOne
{
public class IndexerExample
{
int[] testValue = new int[5];

public int this[int index]
{
get
{
return testValue[index];
}
set
{
testValue[index] = value;
}
}
}
class Program
{
static void Main(string[] args)
{
IndexerExample IE = new IndexerExample();
IE[0] = 200;
Console.Write("{0}", IE[0]);
Console.Read();
}
}
}

Properties Vs Indexers:
static properties can be used without instantiating the class, A static property can
access static members of a class only. we cant define static Indexers.
properties identified by name where as indexers identified by signature.
Below are the difference between properties and indexers.




























Overloading

Inheritance

Overriding

abstract

can have Static

properties

NO

YES

YES

YES

YES

Indexers

YES

YES

YES

YES

NO

No comments:

Post a Comment