Merging .Net 1.1 and 2.0 code, or abusing the type system...
If you've a code that you want to use for .Net 1.1, but still use features from .Net 2.0 (because they are such fun), you usually end with a bunch of #ifdef all over the place, or you create a second class and delegate functionality. It occured to me that C# allows a funky way to combine this functionality without too much bother.
The idea is only applicable where you've a class that you want to be generic in .Net 2.0, and use System.Object on 1.1, this is the case in quite a bit of scenarios, actually. Here is the code:
        #if !dotNet2
        using T = System.Object;
        #endif
                
        public class FunkyClass         
        #if dotNet2             
            <T>         
        #endif
        {
            T _item;
                
            public T Item
            {
                get { return _item; }
                set { _item = value; }
            }
                
            public FunkyClass(T item)
            {
                this._item = item;
            }           
}
This relies on a aliasing the System.Object type to T, so your code can refer to T, and it will mean either System.Object ( in 1.1 ) or the generic type ( in 2.0 ).
 

Comments
Comment preview