Set and Get method

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi ALL,

I am a very new to .NET.

When I want to create a setter or getter.

It is normally wrote :

public type Name{
get{
return defination;
}
set{
defination = value;
}
}

but if I this class holds a Collection,
I want to get some item by parameter, let me say:

public Type getItem(string byName);
public Type getItem(int byIndex);

How to write like setter and getter.

Thanks
 
It's called an indexer. Look it up in Google (or in Studio '05 just type
inderer and hit Tab twice and it will create one).
 
Try something like this:

class MyCustomCollection {
// I will leave you to figure out the internal storage for your
collection

public Item this[int index] {
get {
return itemList[index];
}
set {
itemList[index] = value;
}
}

public Item this[string name] {
get {
foreach(Item itm in itemList) {
if(itm.Name.Equals(name)) {
return itm;
}
return null;
}
set {
for(int i=0;i<itemList.Length;i++) {
if(itemList.Name.Equals(name)) {
itemList = value;
}
}
}
}


Usage:

MyCustomCollection coll = new MyCustomCollection();
coll[0] = new Item(...);
coll["newName"] = new Item(...);

CAUTION: The item's Name property must be unique

--
Neil Cowburn
Principal Partner
OpenNETCF Consulting, LLC.

http://www.opennetcf.com/
 
Perfect,Cool

Thanks

It's called an indexer. Look it up in Google (or in Studio '05 just type
inderer and hit Tab twice and it will create one).


--
Chris Tacke - Embedded MVP
OpenNETCF Consulting
Managed Code in the Embedded World
www.opennetcf.com
 
More cool,

Thanks you guys.


Neil Cowburn said:
Try something like this:

class MyCustomCollection {
// I will leave you to figure out the internal storage for your
collection

public Item this[int index] {
get {
return itemList[index];
}
set {
itemList[index] = value;
}
}

public Item this[string name] {
get {
foreach(Item itm in itemList) {
if(itm.Name.Equals(name)) {
return itm;
}
return null;
}
set {
for(int i=0;i<itemList.Length;i++) {
if(itemList.Name.Equals(name)) {
itemList = value;
}
}
}
}


Usage:

MyCustomCollection coll = new MyCustomCollection();
coll[0] = new Item(...);
coll["newName"] = new Item(...);

CAUTION: The item's Name property must be unique

--
Neil Cowburn
Principal Partner
OpenNETCF Consulting, LLC.

http://www.opennetcf.com/


jeff said:
Hi ALL,

I am a very new to .NET.

When I want to create a setter or getter.

It is normally wrote :

public type Name{
get{
return defination;
}
set{
defination = value;
}
}

but if I this class holds a Collection,
I want to get some item by parameter, let me say:

public Type getItem(string byName);
public Type getItem(int byIndex);

How to write like setter and getter.

Thanks
 
Back
Top