Skip to content

🎹 HW 5: Enumerations

Assignment Deadline

This assignment is due Friday, September 27th on Brightspace

Submit

via GIPHY

Object-Oriented Programming

C# is an object-oriented programming language, meaning that the code we write is organized into little blocks. Each object has its own data and capabilities such as variables and methods. These objects then work together to form a system. Object-oriented programming allows us to separate large programs into individual components called objects, each responsible for a small slice of the overall program. Objects belong to a class, which defines a category of things with the same structure and capabilities.

The basic concept of object-oriened programming is that instead of putting all of our code into a single ever-growing blob of code, we split our program into multiple components called objects. Each object has a singly responsible for something and then collaborate t ogether to solve some problem.

The four basic principles of object-oriented programming are:

  • Abstraction: Modeling the relevant attributes and interactions of entities as classes to define an abstract representation of a system.
  • Encapsulation: Hiding the internal state and functionality of an object and only allowing access through a public set of functions.
  • Inheritance Ability: to create new abstractions based on existing abstractions.
  • Polymorphism Ability: to implement inherited properties or methods in different ways across multiple abstractions.

Some key points of OOP:

  • Objects can be created/discarded while the program runs. When an object is no longer needed it can be removed
  • Objects contain methods and variables. The variables store it data. The methods allow other objects to make requests to it
  • Objects can communicate or coorinate with othe objects by calling one of its methods
  • In C#, every object belongs to a specific class or type
  • Several objects can belong to the same class. Objects of a particular class are called instances of a class
  • There are many predefined classes of objects that exist a part of .NET and/or Unity. However, we can always define our own new classes as well
  • C# provides support on how we can define new types from built-in ones, including enumerations, tuples, structs, and classes

Enumerations

In C#, types are important and so far we have used some common data types such as int and string.

Enumereations are types that are useful when we have a relatively small set of choices. They are custom types that lists the set of allowed values: enum Season { Winter, Spring, Summer, Fall }. We define enumerations always after our all our methods or in a separate file on its own. After defining your enumeration, you are able to use it as variable's type: Season now = Season.Winter;

How do we define an enumeration?

An enumeration type (or enum type) is a value type defined by a set of named constants of the underlying integral numeric type. To define an enumeration type, use the enum keyword and specify the names of enum members. In the example below, we define a new enumeration by starting with the enum keyword, followed by the enumeration's name (Season). A set of curly braces contains the options for the enumeration, separated by commas. In C#, remember that it is common practice to use UpperCamelCase for type names (such as enumerations) and enumeration numbers. The first item you list will be the enumeration's default value!

DeclaringEnums.cs
1
2
3
4
5
6
7
8
// Declaring a new enumeration to represent seasons
enum Season
{
    Spring,
    Summer,
    Autumn,
    Winter
}

With our Season emumeration defined, w can use it like any other type. For example, we can declare a variable whose type is Season.

// Declaring a variable with type Season
Season current;

The compiler can also help us enforce that only legitimate seasons are assigned to this varible. In the example below, we have access to a specific enumeration value through the enumeration type name and the dot operator.

// Declaring a new enumeration to represent seasons
Season current = Season.Summer;

By default, the associated constant values of enum members are of type int; they start with zero and increase by one following the definition text order. You can explicitly specify any other integral numeric type as an underlying type of an enumeration type. You can also explicitly specify the associated constant values, as the following example shows:

DeclaringEnums.cs
1
2
3
4
5
6
7
8
// Declaring an enumeration type
enum ErrorCode : ushort
{
    None = 0,
    Unknown = 1,
    ConnectionLost = 100,
    OutlierReading = 200
}

You cannot define a method inside the definition of an enumeration type. To add functionality to an enumeration type, create an extension method.

Tuples

Tuples in C# are only used occasionally. However, they are useful in combining mulitple pieces into a single element. They combine multiple elements into a single bundle: (double, double) point = (2, 4);. They are sometimes referred to by the number of items in them: a 2-tuple if it has two t hings, an 8-tuple if it has eight things, etc. Tuples are value types, like int, bool, and double. That means they store their data inside them. Assigning one variable to another will copy all the data from all the items in the process. That is made a bit more complicated because tuples are composite types. If a tuple has parts that are value types themselves, those byptes will get copied. But if an item is a reference type, then the reference is copied.

Forming a new tuple value - you can take the pieces you need and place them in parantheses, separated by commas.

// Forming a new tuple value
(string, int, int) score = ("Debbie", 20, 15);

// Forming a variable type
var score = ("Debbie", 20, 15);

// Access the items inside a tuple
Console.WriteLine($"Name:{score.Item1} Level:{score.Item3} Score:{score.Item2}");

// Tuple with different types
(string, int, int) score1 = ("Debbie", 20, 15);
(string, int, int) score2 = score1;

What about deconstructing or taking apart tuples?

var score = (Name: "Debbie", Points: 20, Level: 15);

// Grab data out of a tuple by referencing the item by name
string playerName = score.Name;

When you only need a single item from the tuple, this is a good way to do it.

Deconstruction or unpacking is a way to take all of the parts of a tuple and place them each into separate variables all at once. Tuple deconstruction has many uses, but a clever usage is swapping the contents of two variables. It is done by listing each of the variables to store the deconstructed tuple in parentheses:

string name;
int points;
int level;

(name, points, level) = score;
Console.WriteLine($"{name} reached level {level} with {points} points.");

// Can also write the above lines like this
(string name, int points, int level) = score;

Problems

We will be continuing with our programming assignments off of your own forked repositories. In order to grab the latest homework assignment, please sync your branch with Debbie's original repository which can be found at the following link: https://github.com/debbieyuen/ctin583-fa24-hw/.

Problem 1: Switches

The switch statement selects a statement list to execute based on a pattern match with a match expression. The switch statement is a multiway branch statement that provides an efficient way to transfer the execution to different parts of a code based on the value of the expression. The switch expression is of integer type such as int, char, byte, or short, or of an enumeration type, or of string type. The expression is checked for different cases and the one match is executed.

Problem 1: Switch Statements

Finish the case statements for each collectible item listed in CollectibleItems.cs.

Problem 2: Calling Enums

Problem 2: Calling Enumerations

Currently each case statement is written as a string. Enums are especially helpful in preventing spelling mistakes. Instead of using strings such as "Enemy" and "Gem", lets use an enum. Please modify each case statement to use an enum instead.

Problem 3: Tuples

Problem 3: Tuples

Define a normal tuple and a value tuple. When would you use a value tuple? Print out each value in your defined tuple with Debug.Log

Problem 4: Enums

Problem 2: Enumerations

Define a new enum within this file taking in different types of particles. Examples include: FireParticles, GoldRibbons, Snowflakes, RainParticles, etc.

Problem 5: Short Answers

An important part of learning is feeling comfortable researching, looking stuff up, debugging problems, and reading documentation. Please do your own research to answer the questions in this section. In your CollisionHandler.cs file, please write short answers between 2 - 5 sentences for the following questions:

Problem 5: Short Response Questions

  • When would you use a tuple over a struct?
  • How do we acces items in a tuple?
  • Try visualizing your enum in the Unity Editor. How does it appear as?

Submission

CTIN 583 Survey

Please fill out this anonymous survey about the course so far!

GitHub Pull Requests

To receive credit for this homework assignment, please Jerry and Debbie as Reviewers and Assignees when you hit the green Create Pull Request button.

Image title

Image title

Image title