12.10. Controlling Additions to an ArrayList Through Attributes

Problem

You need to allow only certain types of items to be stored within an ArrayList or an ArrayList-derived container, and it is likely that more types will be added to this list of allowed types in the future. You need the added flexibility to mark the types that are allowed to be stored in the ArrayList as such, rather than changing the container.

Solution

First, create a new attribute to mark the types that are allowed to be stored in the ArrayList. The following code defines the AllowedInListAttribute attribute:

using System;

[AttributeUsage(AttributeTargets.Interface | AttributeTargets.Struct | 
        AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
public class AllowedInListAttribute : Attribute
{
    public AllowedInListAttribute( ) {} 

    public AllowedInListAttribute(bool allow) 
    {
        allowed = allow;
    }

    // by defaulting to false, we default the usage to preventing the 
    // use of the type.
    private bool allowed = false;

    public bool IsAllowed
    {
        get {return (allowed);}
        set {allowed = value;}
    }
}

Next, mark all classes that can be stored in the ArrayList with this attribute:

[AllowedInListAttribute(true)]
public class ItemAllowed {}

[AllowedInListAttribute(true)]
public class Item {}

In addition, this attribute allows types to be disallowed from being stored in the ArrayList by passing false to its constructor or by not passing an argument to the attribute constructor or not applying the attribute:

[AllowedInListAttribute(false)] ...

Get C# Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.