As mentioned in the comments this is simply a case of method chaining. Using the result of one method call the next method and so on.
To make it super clear let's break the code apart to see what's going on.
var keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.W))
{
}
There's actually quite a few things going on here. In MonoGame the Keyboard
class is static so its methods can be called from anywhere. When you call GetState()
it returns an instance of the KeyboardState
class which holds a copy of the state of the keys at the time the method was called.
The IsKeyDown
method returns a bool
which is why it can be used in the if
statement to check if the key is actually down.
Hopefully once you compare the original code to the broken apart code you can see how method chaining can be used in all sorts of scenarios. Sometimes it makes the code easier to understand to have it broken apart like this and other times it's just as easy to grasp with several chained methods together (you'll often find this with LINQ code).
However, there is one important distinction here. What happens when you want to check multiple key combinations at once? This code:
if (Keyboard.GetState().IsKeyDown(Keys.W))
{
}
if (Keyboard.GetState().IsKeyDown(Keys.S))
{
}
Is actually not the same as this code:
var keyboardState = Keyboard.GetState();
if (keyboardState.IsKeyDown(Keys.W))
{
}
if (keyboardState.IsKeyDown(Keys.S))
{
}
The reason is that calling Keyboard.GetState()
will actually do work to fetch the state of the keyboard each time the method is called. Technically that means the state of the pressed keys could have changed between calls to GetState
.
Most of the time this won't really matter because the code will execute fast enough that it won't be noticeable. But it's important to understand this distinction because I've seen scenarios when calling GetState
in two different parts of the code can cause some weird bugs. Particularly if you're holding a copy of the "previous state" to check if keys have changed state between frames.
So, even though you can method chain like this I wouldn't recommend it in this case. You'll have a lot less headaches if you only call GetState
once each frame and reuse that state throughout your game code.