views:

450

answers:

2

I have a generic class definition similar to this:

public sealed class MyClass<TProperty,TOwner>
{
    ...
}

Now I'd like any instances of MyClass<TProperty,TOwner> regardless of the types of TProperty or TOwner to share a Hashtable. I thought of creating an internal MyClassBase with a protected internal static field of type Hashtable and inherit from that. I really only want the definition of MyClass to have access to this hashtable.

Is this a sound approach? I can't seal MyClassBase, so this probably could lead to opening a can of worms later on...

Are there other approaches for this?

+3  A: 

The protected static Hashtable is a fine approach (make sure you synchronize it). You can't have an internal base class whose derived classes are public - but you can prevent it from being derived outside your assembly by making its default constructor internal:

public abstract class MyBaseClass
{
    internal MyBaseClass() { }

    private static Hashtable _hashtable;

    protected static Hashtable Hashtable
    {
        get
        {
            if(_hashtable == null)
            {
                _hashtable = Hashtable.Synchronized(new Hashtable());
            }
            return _hashtable;
        }
    }
}
Rex M
Oi, yeah, not enough sleep, an internal class is obviously less accessible than a public class.I have synchronized locks... Thanks for the internal constructor tip...
kitsune
A: 

Another option is to make an internal static class with an exposed member, and only access it from MyClass<T,U>. Sure, it'd be visible within your assembly, but that's easily controlled compared to a protected member. Just make sure to only use it in your MyClass<T,U> and it'll be fine.

280Z28