views:

45

answers:

2

Hi all. 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.}"

Any suggestions?

EDIT: 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;
            }
        }
    }
}
+2  A: 

There is an inheritance demand on the WeakReference class, and the Silverlight runtime doesn't have the necessary permissions. So you can't inherit WeakReference in Silverlight...

[SecurityPermissionAttribute(SecurityAction.InheritanceDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]
Thomas Levesque
+4  A: 

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 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((object)target, trackResurrection);
        }

        public T Target
        {
            get
            {
                return (T)this.inner.Target;
            }
            set
            {
                this.inner.Target = value;
            }
        }

        public bool IsAlive {
            get {
                 return this.inner.IsAlive;
            }
        }
    }
}
BC
Simple and efficient workaround, +1. However, I think you also need a IsAlive property ;)
Thomas Levesque
You're right, thanks.
BC