Game Development Reference
In-Depth Information
You might also want to check out the .NET/Mono delegate framework through the System.Action class.
Note
A sample project demonstrating delegates can be found in the topic's companion files at
Chapter10/Delegates/ .
Write Shorter Code
The famous computer scientist Ken Thompson is often attributed as saying, “One of my most
productive days was throwing away 1000 lines of code.” And another computer scientist, Edsger
W. Dijkstra, echoed a similar idea when he said, “Simplicity is a prerequisite for reliability.” Here,
there's the idea that simplicity is preferred wherever possible. In programming, this often means
not resorting to needless complexity and excess; and keeping your code shorter, tidier, and more
readable, while still being reliable and efficient. Achieving this in practice is actually harder than it
sounds, and it's often something you develop with experience. But there are tips and techniques
you can use right now to write shorter and clearer C# code that's often easier to read and maintain.
Some general tips follow.
Ternary Operator
The term ternary is Latin, meaning “composed of three parts.” This name describes the three-part
nature of the ternary operator in C#, which is essentially a form of abbreviation. It is sometimes call
the conditional operator . Often, when coding games, you'll need to check a specific condition using
an if-else statement. Then, based on the outcome of the check, you'll need to assign a variable
some specific value, in both the if and the else blocks; something like what's shown in Listing 10-10.
Listing 10-10. Assigning Variables Based on Conditions
if(DoorClosed == true)
{
MonsterState = MONSTER_STATE.Idle;
}
else
{
MonsterState = MONSTER_STATE.Attack;
}
The ternary operator lets you shorten code like this into only one line using the ? and the : symbols.
Using the ternary operator, Listing 10-10 could be abbreviated into Listing 10-11.
Listing 10-11. Using the Ternary Operator
DoorClosed = (DoorClosed == true) ? MONSTER_STATE.Idle : MONSTER_STATE.Attack;
 
Search WWH ::




Custom Search