Creating a strongly-typed c# collection

  • Thread starter Thread starter Sefa Sevtekin
  • Start date Start date
S

Sefa Sevtekin

I am trying to create a c# typesafe collection to avoid
typecasting exceptions and to ease binding of grids to
collections. I already did it in VB.NET but couldn't map
it to C#. In VB.NET you need to define a default property
in order to make binding work. It is something similiar to
this:

Default Public ReadOnly Property Item(ByVal index As
Integer) As LineItem
Get
Return CType(list(index), LineItem)
End Get
End Property

As far as I know there is no Default identifier for C#
properties.

Any help would be appriciated!!!

Sefa
 
Sefa,

Default properties are BAAAAD. =)

Anyways, the equivalent in C# is by creating an indexer, like this:

public LineItem this[int index]
{
get
{
return (LineItem) list[index];
}
}

Hope this helps.
 
I found the answer for my own question. I've gotta use an
indexer. For the ones who has the same problem, here is a
little example I found on the web:

public class BeerInventory :
System.Collections.CollectionBase
{

public int Add(Beer value)
{
return List.Add(value);
}

public Beer this[int index]
{
get
{
return (Beer)List[index];
}
set
{
List[index] = value;
}
}
}
 
One other question; I am trying to bind it to a data grid
like:

BeerInventory inventory = new BeerInventory();
inventory.Add(new Beer
("Hamms", "Hamms Brewing Co.", 3));
inventory.Add(new Beer
("Budweiser", "Anheuser-Busch", 1000));
inventory.Add(new Beer("Mulholland
Rain", "City Brewers", 113));
button1.Text = inventory[1].name;

dataGrid1.DataSource = inventory;

The grid doesn't show the records.Any idea??




-----Original Message-----
Sefa,

Default properties are BAAAAD. =)

Anyways, the equivalent in C# is by creating an indexer, like this:

public LineItem this[int index]
{
get
{
return (LineItem) list[index];
}
}

Hope this helps.


--
- Nicholas Paldino [.NET/C# MVP]
- (e-mail address removed)

I am trying to create a c# typesafe collection to avoid
typecasting exceptions and to ease binding of grids to
collections. I already did it in VB.NET but couldn't map
it to C#. In VB.NET you need to define a default property
in order to make binding work. It is something similiar to
this:

Default Public ReadOnly Property Item(ByVal index As
Integer) As LineItem
Get
Return CType(list(index), LineItem)
End Get
End Property

As far as I know there is no Default identifier for C#
properties.

Any help would be appriciated!!!

Sefa


.
 
Back
Top