invisal
invisal

Reputation: 11171

Set ReadOnly Property from collection class

It is little hard to explain what I want, but basically, I want to set a ReadOnly property from a collection class. I know it is not that simple.

public class ListItemCollection : CollectionBase {
      // other code

      public void Add(ListItem item) {
            item.Index = List.Count;  // want to set Index
            List.Add(item);
      }
}

I don't want other class from ListItemCollection to change the value of that property.

public class Form1 : Form
{
     private void Form_Load(....) {
          ListItem item = new ListItem;
          item.Index = 5; // I don't want people to set it.
     }

}

I know that it is possible somehow because ListViewItem manage to do it.

Upvotes: 2

Views: 74

Answers (2)

Tim S.
Tim S.

Reputation: 56536

You should probably use internal for the set. This makes it accessible from classes in the same assembly, but not from outside it.

public int Index { get; internal set; }

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

You can do it if you place ListItem in the same assembly as ListItemCollection, and give the Index property a public getter and an internal setter:

class ListItem {
    // other code
    public int Index {get; internal set;}
}

Technically, it wouldn't make the property readonly, but as far as the other users of the ListItem class are concerned, the property would appear to have no setter.

If ListItem must be in a different assembly, you could let the ListItemCollection class see the setter by using the InternalsVisibleTo attribute.

Upvotes: 3

Related Questions