943,628 Members | Top Members by Rank

Ad:
  • C# Discussion Thread
  • Unsolved
  • Views: 395
  • C# RSS
May 3rd, 2009
0

Indexers

Expand Post »
I don't understand the indexers Can any one explain it to me
Similar Threads
Reputation Points: 10
Solved Threads: 0
Light Poster
Egypt Pharaoh is offline Offline
40 posts
since Dec 2008
May 3rd, 2009
0

Re: Indexers

Can you understand this? http://msdn.microsoft.com/en-us/library/6x16t2tx.aspx
It seems a good explanation to me. If it ain't clear, please come back with your questions.
Reputation Points: 2023
Solved Threads: 644
Senior Poster
ddanbe is offline Offline
3,735 posts
since Oct 2008
May 4th, 2009
0

Re: Indexers

Dear,

An indexer is a member of class that enables an object to be indexed in the same way as an array.

Consider the following code:
Quote ...
using System;

public class Date
{
int d, m, y;

// Constructors
public Date()
{
d = DateTime.Now.Day;
m = DateTime.Now.Month;
y = DateTime.Now.Year;
}
public Date(int d, int m, int y)
{
this.y = y;
this.m = m;
this.d = d;
}

// Properties
public int Day
{
get { return d; }
set { d = value; }
}
public int Month
{
get { return m; }
set { m = value; }
}
public int Year
{
get { return y; }
set { y = value; }
}

public string DMY
{
get
{
return d + "-" + m + "-" + y;
}
}
public string MDY
{
get
{
return m + "-" + d + "-" + y;
}
}

// Indexers
public int this[string i]
{
get
{
if (i == "day")
return d;
else
if (i == "month")
return m;
else
return y;
}
set
{
if (i == "day")
d = value;
if (i == "month")
m = value;
if (i == "year")
y = value;
}
}
public int this[int i]
{
get
{
if (i == 0)
return d;
else
if (i == 1)
return m;
else
return y;
}
set
{
if (i == 0)
d = value;
if (i == 1)
m = value;
if (i == 2)
y = value;
}
}

}


class MainApp
{
static void Main()
{
Date k = new Date();

Console.WriteLine(k.DMY);
Console.WriteLine(k.MDY);
k.Day = 8;
Console.WriteLine(k.DMY);

k[0] = 10;
k[1] = 3;
k[2] = 2010;

Console.WriteLine(k[0]);

k["month"] = 2;

Console.WriteLine(k["day"] + "-" + k["month"] + "-" + k[2]);

// Another example with string object
string name = "Hello";
Console.WriteLine(name[1]);
}
}
Moderator
Reputation Points: 2136
Solved Threads: 1228
Posting Genius
adatapost is offline Offline
6,527 posts
since Oct 2008

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C# Forum Timeline: Saving Images into the database
Next Thread in C# Forum Timeline: Using stored procecure in MYSQL





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC