Reader small image

You're reading from  Learning C# by Developing Games with Unity - Seventh Edition

Product typeBook
Published inNov 2022
Reading LevelBeginner
PublisherPackt
ISBN-139781837636877
Edition7th Edition
Languages
Tools
Right arrow
Author (1)
Harrison Ferrone
Harrison Ferrone
author image
Harrison Ferrone

Harrison Ferrone is an instructional content creator for LinkedIn Learning and Pluralsight, tech editor for the Ray Wenderlich website, and used to write technical documentation on the Mixed Reality team at Microsoft. He is a graduate of the University of Colorado at Boulder and Columbia College, Chicago. After a few years as an iOS developer at small start-ups, and one Fortune 500 company, he fell into a teaching career and never looked back.
Read more about Harrison Ferrone

Right arrow

Exploring Generics, Delegates, and Beyond

The more time you spend programming, the more you start thinking about systems. Structuring how classes and objects interact, communicate, and exchange data are all examples of systems we’ve worked with so far; the question now is how to make them safer and more efficient.

Since this will be the last practical chapter of the book, we’ll be going over examples of generic programming concepts, delegation, event creation, and error handling. Each of these topics is a large area of study in its own right, so take what you learn here and expand on it in your projects. After we complete our practical coding, we’ll finish up with a brief overview of design patterns and how they’ll play a part in your programming journey going forward.

We’ll cover the following topics in this chapter:

  • Generic programming
  • Using delegates
  • Creating events and subscriptions
  • Throwing and handling errors...

Introducing generics

All of our code so far has been very specific in terms of defining and using types. However, there will be cases where you need a class or method to treat its entities in the same way, regardless of its type, while still being type-safe. Generic programming allows us to create reusable classes, methods, and variables using a placeholder, rather than a concrete type.

When a generic class instance is created at compile time or a method is used, a concrete type will be assigned, but the code itself treats it as a generic type. Being able to write generic code is a huge benefit when you need to work with different object types in the same way, for example, custom collection types that need to be able to perform the same operations on elements regardless of type, or classes that need the same underlying functionality.

We’ve already seen this in action with the List type, which is a generic type. We can access all its addition, removal, and modification...

Delegating actions

There will be times when you need to pass off, or delegate, the execution of a method from one file to another. In C#, this can be accomplished through delegate types, which store references to methods and can be treated like any other variable. The only caveat is that the delegate itself and any assigned method need to have the same signature—just like integer variables can only hold whole numbers and strings can only hold text.

Creating a delegate is a mix between writing a function and declaring a variable:

public delegate returnType DelegateName(int param1, string param2);

You start with an access modifier followed by the delegate keyword, which identifies it to the compiler as a delegate type. A delegate type can have a return type and name as a regular function, as well as parameters if needed. However, this syntax only declares the delegate type itself; to use it, you need to create an instance as we do with classes:

public DelegateName...

Firing events

C# events allow you to essentially create a subscription system based on actions in your games or apps. For instance, if you wanted to send out an event whenever an item is collected, or when a player presses the spacebar, you could do that. However, when an event fires, it doesn’t automatically have a subscriber, or receiver, to handle any code that needs to execute after the event action.

Any class can subscribe or unsubscribe to an event through the calling class the event is fired from; just like signing up to receive notifications on your phone when a new post is shared on Facebook, events form a kind of distributed-information superhighway for sharing actions and data across your application.

Declaring events is similar to declaring delegates in that an event has a specific method signature. We’ll use a delegate to specify the method signature we want the event to have, then create the event using the delegate type and the event keyword:

...

Handling exceptions

Efficiently incorporating errors and exceptions into your code is both a professional and personal benchmark in your programming journey. Before you start yelling “Why would I add errors when I’ve spent all this time trying to avoid them?!”, you should know that I don’t mean adding errors to break your existing code. It’s quite the opposite—including errors or exceptions and handling them appropriately when pieces of functionality are used incorrectly makes your code base stronger and less prone to crashes, not weaker.

Throwing exceptions

When we talk about adding errors, we refer to the process as exception throwing, which is an apt visual analogy. Throwing exceptions is part of something called defensive programming, which essentially means that you actively and consciously guard against improper or unplanned operations in your code. To mark those situations, you throw out an exception from a method that is then...

Summary

While this chapter brings us to the end of our practical adventure into C# and Unity 2022, I hope that your journey into game programming and software development has just begun. You’ve learned everything from creating variables, methods, and class objects to writing your game mechanics, enemy behavior, and more.

The topics we’ve covered in this chapter have been a level above what we dealt with for the majority of this book, and with good reason. You already know your programming brain is a muscle that you need to exercise before you can advance to the next plateau. That’s all generics, events, and design patterns are: just the next rung up the programming ladder.

In the next chapter, I will leave you with resources, further reading, and lots of other helpful (and, dare I say, cool) opportunities and information about the Unity community and the software development industry at large.

Happy coding!

Pop quiz—intermediate C#

  1. What is the difference between a generic and non-generic class?
  2. What needs to match when assigning a value to a delegate type?
  3. How would you unsubscribe from an event?
  4. Which C# keyword would you use to send out an exception in your code?

Don’t forget to check your answers against mine in the Pop Quiz Answers appendix to see how you did!

Join us on discord!

Read this book alongside other users, Unity game development experts and the author himself.

Ask questions, provide solutions to other readers, chat with the author via. Ask Me Anything sessions and much more.

Scan the QR code or visit the link to join the community.

https://packt.link/csharpwithunity

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning C# by Developing Games with Unity - Seventh Edition
Published in: Nov 2022Publisher: PacktISBN-13: 9781837636877
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at AU $19.99/month. Cancel anytime

Author (1)

author image
Harrison Ferrone

Harrison Ferrone is an instructional content creator for LinkedIn Learning and Pluralsight, tech editor for the Ray Wenderlich website, and used to write technical documentation on the Mixed Reality team at Microsoft. He is a graduate of the University of Colorado at Boulder and Columbia College, Chicago. After a few years as an iOS developer at small start-ups, and one Fortune 500 company, he fell into a teaching career and never looked back.
Read more about Harrison Ferrone