2

What makes MSpec require only static fields? For example, the code here causes an error

public class When_not_enabled
{
    private static ActionExecutingContext filterContext;

    // On purpose I've made subject non static
    private CompleteOrderGuardFilter subject;

    Establish context = () =>
    {
        // Here I get cannot access non static field in static context
        subject = new CompleteOrderGuardFilter(null, false);
        filterContext = new ActionExecutingContext();
    };
}

Error:

cannot access non static field in static context

Anthony Mastrean
  • 21,850
  • 21
  • 110
  • 188
hvd
  • 27
  • 2
  • http://stackoverflow.com/a/18157580/43846 – stuartd Feb 04 '15 at 13:59
  • two delegates defined public delegate void Establish(); public delegate void It(); and a method like void Method() { Establish xx = () => a.State = "1"; It yy = () => a.State = "2"; } No need that "a" to be static. The question - underneath the surface how is mspec imposing this ? – hvd Feb 04 '15 at 14:05

1 Answers1

1

MSpec does not instantiate the context class but rather calls the Establish/Because/It/Cleanup delegates directly. As such, there is no state (class instance) created and you need all information you want to pass between the delegates to be globally available, e. g. static.

Alexander Groß
  • 10,200
  • 1
  • 30
  • 33
  • Hello. I understand the need for it. What I am not getting, from implementation point of view, how is the compiler instructed to force the fields to be static ? – hvd Feb 05 '15 at 07:33
  • The compiler forces access to static fields itself. This is due to the C# language design. – Alexander Groß Feb 07 '15 at 10:28