title: casting to an abstract generic base class
body: <p>I have an abstract generic class that inherits from the Mvc <strong>Controller</strong> uses the generic type to create a dictionary of items, similar to this:</p>
  
  <pre><code>public abstract class BaseController&lt;TElement&gt; : Controller where TElement : BaseElement
  {
      public Dictionary&lt;string, TElement&gt; Stuff { get; set; }
      string Name;
  
      public BaseController()
      {
          this.Name = Helper.GetName();
          this.Stuff = Helper.GetStuff(Name) as Dictionary&lt;string, TElement&gt;;
      }
  }
  </code></pre>
  
  <p>I then have several different implementations of BaseControllers that pass in different types of BaseElement, based on a criteria that names the object (I believe this part is irrelevant, but please let me know if it's affecting my end result).</p>
  
  <p>The problem is later I need to check if the "Stuff" property is null from an actionfilter, which accesses instances of BaseController through the base Mvc Controller property. </p>
  
  <pre><code>public override void OnActionExecuting(ActionExecutingContext filterContext)
  {
      var controller = filterContext.Controller as **BaseWidgetController**; // &lt;-- here
      if (controller == null)
          throw new Exception(filterContext.Controller.GetType().ToString());
  }
  </code></pre>
  
  <p>My "BaseController" is a controller, so it does fit into that property, but I can't figure out how to cast it to my BaseController type to get the Stuff property...</p>
  
  <p>Can this be done? I've seen while searching mention of covariance, but I can't seem to get my head around it, is that what I need to make this work?</p>
  
  <p>I also saw using reflection as a solution but that is expensive and won't work for my particular situation.</p>
  
  <p>finally I saw that this could work if I defined the base as an Interface instead of abstract class, but I need that base behavior as it will be shared across all inherited types...</p>
  
  <p>The main reason I'm typing this question out is because SO always comes up with great similar questions and i usually just end up finding my answer, but this time I'm really lost with the covariance and generics, so I could use some insight as to whether or not this is even possible, or if I should be doing this in a completely different way...</p>