Indexer S
Indexer S
Overview
Using Properties
Using Indexers
Using Properties
Properties provide:
A useful way to encapsulate information inside a class
Concise syntax
Flexibility
Using Accessors
Similarities
Both contain code to be executed
Both can be used to hide implementation details
Both can be virtual, abstract, or override
Differences
Syntactic – properties do not use parentheses
Semantic – properties cannot be void or take arbitrary
parameters
Property Types
Read/write properties
Have both get and set accessors
Read-only properties
Have get accessor only
Are not constants
Write-only properties – very limited use
Have set accessor only
Static properties
Apply to the class and can access only static data
Property Example
public
public class
class Console
Console
{{
public
public static
static TextReader
TextReader In In
{{
get
get {{
if
if (reader
(reader ==
== null)
null) {{
reader
reader == new
new StreamReader(...);
StreamReader(...);
}}
return
return reader;
reader;
}}
}}
...
...
private
private static
static TextReader
TextReader reader
reader == null;
null;
}}
Using Indexers
What Is an Indexer?
Comparing Indexers to Arrays
Comparing Indexers to Properties
Using Parameters to Define Indexers
String Example
BitArray Example
What Is an Indexer?
Similarities
Both use array notation
Differences
Indexers can use non-integer subscripts
Indexers can be overloaded—you can define several
indexers, each using a different index type
Indexers are not variables, so they do not denote
storage locations—you cannot pass an indexer as a ref
or an out parameter
Comparing Indexers to Properties
Similarities
Both use get and set accessors
Neither have an address
Neither can be void
Differences
Indexers can be overloaded
Indexers cannot be static
Using Parameters to Define Indexers
class
class String
String
{{
public
public char
char this[int
this[int index]
index]
{{
get
get {{
if
if (index
(index << 00 ||
|| index
index >=
>= Length)
Length)
throw
throw new
new IndexOutOfRangeException(
IndexOutOfRangeException( );
);
...
...
}}
}}
...
...
}}
BitArray Example
class
class BitArray
BitArray
{{
public
public bool
bool this[int
this[int index]
index]
{{
get
get {{
BoundsCheck(index);
BoundsCheck(index);
return
return (bits[index
(bits[index >>>> 5]
5] && (1
(1 <<
<< index))
index)) !=
!= 0;
0;
}}
set
set {{
BoundsCheck(index);
BoundsCheck(index);
if
if (value)
(value) {{
bits[index
bits[index >>>> 5]
5] |=
|= (1
(1 <<
<< index);
index);
}} else {
else {
bits[index
bits[index >>>> 5]
5] &=
&= ~(1
~(1 <<
<< index);
index);
}}
}}
}}
private
private int[
int[ ]] bits;
bits;
}}
Lab 13.1: Using Properties and Indexers
Review
Using Properties
Using Indexers