Search code examples
c#silverlightweak-references

Inherited WeakReference throwing ReflectionTypeLoadException in Silverlight


I'm trying to use a type-safe WeakReference in my Silverlight app. I'm following the recipe on this site: http://ondevelopment.blogspot.com/2008/01/generic-weak-reference.html only using the System.WeakReference and omitting the stuff that references Serialization.

It's throwing a ReflectionTypeLoadException when I try to run it, with this message:

"{System.TypeLoadException: Inheritance security rules violated while overriding member: 'Coatue.Silverlight.Shared.Cache.WeakReference`1..ctor()'. Security accessibility of the overriding method must match the security accessibility of the method being overriden.}"

Here's the code I'm using:

using System;

namespace Frank
{
    public class WeakReference<T>
        : WeakReference where T : class
    {
        public WeakReference(T target)
            : base(target) { }

        public WeakReference(T target, bool trackResurrection)
            : base(target, trackResurrection) { }

        protected WeakReference() : base() { }

        public new T Target
        {
            get
            {
                return (T)base.Target;
            }
            set
            {
                base.Target = value;
            }
        }
    }
}

Solution

  • As Thomas mentioned, you can't inherit from weak reference in silverlight but you can wrap it:

    using System;
    
    namespace Frank
    {
        public class WeakReference<T> where T : class
        {
            private readonly WeakReference inner;
    
            public WeakReference(T target)
                : this(target, false)
            { }
    
            public WeakReference(T target, bool trackResurrection)
            {
                if(target == null) throw new ArgumentNullException("target");
                this.inner = new WeakReference(target, trackResurrection);
            }
    
            public T Target
            {
                get
                {
                    return (T)this.inner.Target;
                }
                set
                {
                    this.inner.Target = value;
                }
            }
    
            public bool IsAlive {
                get {
                     return this.inner.IsAlive;
                }
            }
        }
    }