Skip to content

πŸ“” HW 4: Generics & Inheritence

Assignment Deadline

This assignment is due Friday, September 20th on Brightspace

Submit

via GIPHY

Generics

Generics allow us to create code that is more "generic" so that it can be used and reused. Remember "DRY" in programming? Also known as "Don't Repeat Yourself." Generics are really helpful here in preventing the need for duplicate code - which is always a great thing. They help solve the problem of making classes or methods that would differ only by the types they use, leaving placeholders for types that can be filled in when used.

Generics are created by adding <T> after the class name. <T> represents the generic type that gets set while being called. We can have multiple generic types in a class by separating them with commas like <T, U, V>. When declaring generics in Unity, the general naming convention starts from T and moves alphabetically down as T, U, V, etc. Feel free to make generic methods and gneeric types with multiple type parameters!

To make your life easier, here are some existing and common generic types:

  • Random generates pseudo-random numbers
  • DateTime gets the current time and stores time and date values
  • TimeSpanrepresents a length of time
  • List<T> is a popular and versatile generic collection -- use it instead of arrays for most things
  • IEnumerable<T>is an interface for almost any collection type. The basis for foreach loops
  • Dictionary<TKeym, TValue> can look up one piece of information from another
  • Nullable<T> is a struct that can express the concept of a missing value for value types
  • ValueTuple is the secret sauce behind tuples in C#
  • StringBuilder is a less memory-intensive way to build strings a little at a time

Any type definition that is defined as a generic is a generic type. These include classes, structs, or interfaces that leave placeholders the type it uses. They are similar to methods with parameters where they allow programmers to throw in a value. Below is an example of how you would define a generic type.

// Defining a Generic Type
public class DefineGenericType List<T> {
  private T[] items = new T[0]
  public T Get ItemAt(int index) => items[index];
  public void SetItemAt(int index, T value) => items[index] = value;

  public void Add(T newValue) {
    T[] updated = new T[items.Length + 1];

    for (int index = 0; index < items.Length; index++ ) {
      updated[index] = items[index];
    }

    updated[^1] = newValue;
    items = updated;
  }
}

When we defined the DefineGenericType class above, the <T> served as a placeholder for some type. This placeholder type is called a generic type parameter. It works just like a method parameter, except it works at a higher leve land stands in for a specific type taht will be chosen later. Conveniently, it can be used throughout the class an in several places in your code.

1
2
3
4
5
6
// Generic Class Example
public class GenericClass <T> {
  public Type GetMyType() {
    return typeof (T);
  }
}
The Unity Scripting API Reference documentation lists some functions (for example, the various GetComponent functions) with a variant that has a letter <T> or a type name in angle brackets after the function name. These are generic functions. You can use them to specify the types of parameters and/or the return type when you call the function.

1
2
3
4
void FuncName<T>();
// The type is correctly inferred because it is defined in the function call
var obj = GetComponent<Rigidbody>();
Rigidbody rb = go.GetComponent<Rigidbody>();

Inheritence

Class inheritance means that a class can inherit from any other class that isn't sealed. Other classes can also inherit and override from your class. Classes that inherit must derive from another base class so that it can inherit data and behavior. This base class is specified by appending a colon and the name of the base class bollowing the derived class name. Inheritence lets you derive new classes based on existing ones. The new class inherits everything except constructors from the base class. Inheritence is important in accomplishing two things.

  • Enables the treatment of subtypes as the more generalized type
  • Consolides code that would have otherwise been duplicated or copy-and-pasted

In the C# language, a class can only directly inherit from one base class. You cannot directly derive from moe than one. The class then can directly implement one or more interfaces. By default, all classes inherit from object aka their base class, but you are able to claim a different class as the base class as well.

ClassInheritance.cs
1
2
3
4
5
6
// Declaring an object of type MyClass.
public class Manager: Employee
{
    // Employee fields, properties, methods and events are inherited
    // New Manager fields, properties, methods and events go here
}

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: Generics: 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 BarbieWorld.cs file, please write short answers between 2 - 5 sentences for the following questions:

Problem 1: Generics: Short Answers

  • What is Unity's GetComponent<T>? Why is it considered a generic method?
  • In generics, there is a particular convention we follow in defining generics. What leter do we use to represent a placeholder type or generic? In generics, what are the naming conventions used if we have more than one parameter?
  • What does the generic variable do? Why does it end up as the return type and argument type for a method?
  • Give a realistic and detailed example of when you would want to use generics in your game. When would type variables be useful?
  • What are the performance implications of using generic arrays as opposed to non-generic arrays in C#?
  • What does it mean to instantiate?

Problem 2: Barbie's Careers

Problem 2: Barbie's Careers

Barbie wears many hats. She is a photographer, singer, athlete, painter, musician, rockstar, and much more. What is the function below trying to accomplish? How are we using the T variable in this case? Please instantiate an item of this class in your BarbieWalletBalance.cs file in your Start() or Update() functions.

Problem 3: Barbie's Account

Problem 3: Barbie's Account

Convert the following function to a generic if needed. Then, write a private generic function named BarbieBank. BarbieBank should take in the parameters: numOfPennies, cashAmount, and numOfCreditCards. Have the function return a new generic array with the correct parameters.

Problem 4: Inheritence: Short Answers

Problem 4: Inheritence: Short Answers

  • What is the "Protected" access modifier? How does it relate to inheritence and between two classes.
  • What is MonoBehaviour? Why do Unity C# scripts inherit from MonoBehaviour? Give some examples of Unity functions that come from MonoBehaviour.
  • What is multiple inheritance? Can we perform multiple inheritance in C#? Why or why not?
  • What does "Protected virtual void" mean? When is it needed and what does virtual do in your code?
  • What happens when a constructor in a parent class is called? How do we control which base class contructor is being called?

Problem 5: Barbie's House

Problem 5: Barbie's House

Barbie's House needs to inherit everything from the BarbieWorld class in your BarbieWorld.cs file. Please modify the BarbieHouse class to inherit from BarbieWorld and write at least three methods within BarbieHouse representing furniture, pets, household items, food, etc. within her house.

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

Kitchen Chaos

On BrightSpace, submit a screenshot of where you are at with the Kitchen Chaos tutorial.