Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I try to use first answer of Checking for alternate keys with XNA IsKeyDown but the compiler shows me Extension method must be defined in a non-generic static class. How can I fix this issue?

share|improve this question
3  
Stack Overflow is great for answering these kinds of language questions. –  Kendall Frey Mar 15 '13 at 16:41
4  
Developer pro-tip, Google the error code first: stackoverflow.com/questions/10412233/… –  Byte56 Mar 15 '13 at 16:41
add comment

closed as off topic by Byte56, Tetrad Mar 15 '13 at 17:22

Questions on Game Development Stack Exchange are expected to relate to game development within the scope defined by the community. Consider editing the question or leaving comments for improvement if you believe the question can be reworded to fit within the scope. Read more about reopening questions here.If this question can be reworded to fit the rules in the help center, please edit the question.

1 Answer

The solution proposed by the given answer (http://gamedev.stackexchange.com/a/37637/18568) uses the C# language concept of Extension Methods. These are described in more detail here. What you are doing is effectively 'tacking on' another method to a pre-made class definition that you are unable to modify directly, due to it being supplied as part of a library, or in another form or situation such that the original class should not be edited directly.

To answer your question simply, the snippet of the Any method supplied in the post you linked above is incomplete. By requirement of the C# language, an Extension Method (identified by the use of this as a prefix of the first parameter) must be within a static class. The class type of the method parameter prefixed by this is the class to which the extension method applies; it essentially forces the method to be a member of that class, with the only difference being that the this keyword does not work within the method as it would for a traditional non-static method, and you must instead use the name of the this-prefixed parameter.

#if WINDOWS
namespace MyKeyboardExtensions
{
    public static class MyKeyboardStateExtensionClass
    {
        public static bool Any(this KeyboardState state, params Keys[] keys)
        {
            return keys.Any(state.IsKeyDown);
        }
    }
}
#endif

Following this, you need to make sure that you specify using MyKeyboardExtensions; wherever you want the extension method(s) to take effect. Keep in mind, also, that extension methods cannot access private variables of the extended class, since otherwise they'd just rip a hole in some pretty basic OOP principles.

share|improve this answer
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.