Lance Roberts
Lance Roberts

Reputation: 22842

Use collection properties with member object

If I have a collection, say Cells, and if referenced like so Cells[1,1] it gives me an object of that collection but the member object doesn't have a certain property that the collection object has. Is there a way to call that property from the member? Like as follows, assuming StartPosition is a property of the object class for the collection:

Cells[1,1].StartPosition

or maybe

Cells[1,1].ParentCollection.StartPosition

Upvotes: 0

Views: 167

Answers (2)

Oded
Oded

Reputation: 498914

You can only call properties that are defined on the object you are accessing.

That is, if you want to call a method on the collection, call it on the collection, not on the content of the collection.

You could add a reference to the containing collection to each item you put in it, if you design and construct your classes that way.

Note:

Your notation is array notation, for 2 dimensional arrays. Though arrays are collections, most .NET collections are not considered to be arrays, even if they do have indexers.

Upvotes: 1

Anže Vodovnik
Anže Vodovnik

Reputation: 2345

You could either wrap that in a propert of the Cell or what you are returning. So you'd add this to the Cell class:

public int StartPosition { 
    get { return this.ParentCollection.StartPosition; } 
}

If you can't change the class you can add an extension method, e.g.:

public static class CellExtensions {
 public static int GetStartPosition(this Cell cell) {
   return cell.ParentCollection.StartPosition;
 }
}

Upvotes: 0

Related Questions