O'Reilly logo

C# Cookbook by Jay Hilyard, Stephen Teilhet

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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)] ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required